Backbone.js - data not being populated in collection even though fetch is successful
fetch
is asynchronous, your collection won't yet be populated if you immediately call render
. To solve this problem, you just have to bind the collection reset event (sync event for Backbone>=1.0) to the view render :
theView = Backbone.View.extend({
el: $("#temp"),
initialize: function () {
this.collection = new theCollection();
// for Backbone < 1.0
this.collection.on("reset", this.render, this);
// for Backbone >= 1.0
this.collection.on("sync", this.render, this);
this.collection.fetch();
},
render : function () {
console.log( this.collection.toJSON() );
}
});
Note the third argument of the bind method, giving the correct context to the method: http://documentcloud.github.com/backbone/#FAQ-this