title: Backbone Collection View each
body: <p>I'm new to Backbone.js and getting some trouble with collection view.
  Here's what I'm trying to do:</p>
  
  <pre><code>var customersCollection = new _App.Collections.Customers();
  var customersView = new _App.Views.Customers({collection: customersCollection});
  customersView.render();
  </code></pre>
  
  <p>And here's a view - I can't understand why I cannot iterate over collection:</p>
  
  <pre><code>_App.Views.Customers = Backbone.View.extend({
      render: function() {
          console.log('Here is my collection');
          console.log(this.collection);
          console.log('Now lets iterate over it...');
          _.each(this.collection, function(item) {
              console.log(item);
          }, this);
          console.log('...done');
          return this;
      }
  });
  </code></pre>
  
  <p>What I see in chrome console:</p>
  
  <pre><code>Here is my collection
  child {length: 0, models: Array[0], _byId: Object, constructor: function, url: "/admin/customers/latest.json"…}
      _byId: Object
      length: 5
      models: Array[5]
      __proto__: Surrogate
  Now lets iterate over it...
  ...done 
  </code></pre>
  
  <p>So I can't figure out why I can see a collection but can't each over it.
  Thanks</p>
  
  <p><strong>// SOLVED</strong></p>
  
  <p>I have found why this was going to happen.
  Completely missed that .fetch() is asynchronous, so when render() was called, data were still not present in collection.
  This code works for me now, so I can go on with templates, etc</p>
  
  <pre><code>_App.Views.Customers = Backbone.View.extend({
      initialize: function() {
          this.collection = new _App.Collections.Customers();
          this.collection.on('sync', this.render, this);
          this.collection.fetch();
      },
      render: function() {
          this.collection.each(function(item) {
              console.log(item);
          });
          return this;
      }
  });
  
  new _App.Views.Customers();
  </code></pre>
  
  <p>Regards, Nikolay</p>