I am trying to populate a collection from a simple JSON file as part of learning backbone.js. But I can\'t get it to work.
The AJAX call is made (verified with Fire
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
i believe the problem lies in your json
either you override the parse method on the collection, to work with your json
or you could change the json :)
[{
"description": "Lorem ipsum..."
},
{
"description": "Lorem ipsum..."
}]
i believe this is what your json should look like, just an array of your models.