0

If I loop the collection in the view, it's seems empty, alert dialog don't show up. When I use console.log(this.collection) in this view, it's look ok (16 element in this collection).

My router: (collection url: '/api/employees', this is a rails json output)

Office.Routers.Employees = Backbone.Router.extend({

  routes: {
    "":   "index"
  },


  initialize: function() {
    this.collection = new Office.Collections.Employees();
    this.collection.fetch();
  },

  index: function() {
    var view = new Office.Views.EmployeesIndex({ collection: this.collection });
    view.render();
  }

});

and my index.js view:

Office.Views.EmployeesIndex = Backbone.View.extend({

  render: function() {
    this.collection.each( function( obj ){ alert(obj); } );
  }

});

Edit:

This is the output of the console.log(this.collection) in view : https://i.stack.imgur.com/ZQBUD.png

Edit2:

I thing Rails is the guilty. When I work whit static collection, everything works fine

var collection = new Backbone.Collection([
  {name: "Tim", age: 5},
  {name: "Ida", age: 26},
  {name: "Rob", age: 55}
]);
user1344853
  • 689
  • 1
  • 7
  • 8

2 Answers2

1

collection.fetch() makes an asynchronous request to the server. The index callback doesn't wait for the fetch to return. So your render function is rendering an empty collection.

You need to use the success callback of the fetch method:

index: function() {
  this.collection.fetch({
    success: function(data) {
      var view = new Office.Views.EmployeesIndex({ collection: data });
      view.render();        
    }        
  });
}

Note that the Backbone documentation recommends bootstrapping any initial data you need by including the data in the document itself:

When your app first loads, it's common to have a set of initial models that you know you're going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page.

Rob Flaherty
  • 1,055
  • 6
  • 16
0

The fetch has probably not completed by the time your view renders. Try the following:

  index: function() {
    var p, collection, view;
    collection = new Office.Collections.Employees();
    p = collection.fetch();
    view = new Office.Views.EmployeesIndex({ collection: collection });
    p.done(view.render);
  }
ggozad
  • 13,105
  • 3
  • 40
  • 49