I have a backbone collection. I fetch. The server comes back with a JSON. How do I populate the collection witht he fresh data? Here’s my code:
var Todos = Backbone.Collection.extend({
url: "server/todos-service.php", // this does what it is supposed to do so no worries!
model: Todo,
initialize: function(attributes, options) {
// IN HERE WHAT DO I HAVE TO DO?
// WHAT EVENT SHALL I BIND TO TO REACT THE DATA DELIVERY?
// AND WHAT SHALL I DO NEXT TO POPULATE THE DAMN THINGS
}
});
// CLIENT CODE
new Todos().fetch();
Can anyone tell me how this is supposed to be done?
Cheers
The
fetchwill start the ajax call to your server. When the data is returned it is automatically put the data into your collection, and the collection will fire aresetbeing like “I’m done fetching data bro, you can use it now.”You would usually call fetch() from inside your view, and have the view listen to the
resetevent. When the reset event is trigger, the view renders the collection.Also as a resource, I found this tutorial to be really helpful in understanding the basics of backbone http://net.tutsplus.com/sessions/build-a-contacts-manager-using-backbone-js/