Here I have a Backbone.js Model – Contact and a Collection – Contacts with Contact as the Model. I’ve two views where in one I use collection to list all the contacts and in the second the model directly to show a single contact. But when I’m using the model directly I’m able to get the ‘change’ event fired while using with the collection the ‘change’ event, (even ‘all’ events of the model) is not fired. Am I missing some extra bind here to make it work with collection?
var Contact = Backbone.Model.extend({
defaults: {
id: 0,
urlDisplayPicBig: '',
urlDisplayPicSmall: ''
},
initialize: function () {
this.bind('change', this.doSomething);
},
generateUrls: function () { //earlier doSomething()
...
}
...
});
var Contacts = Backbone.Collection.extend({
model: Contact,
...
});
Update
While using both collection & single model instances I have to run generateUrls() to update urlDisplayPicBig & urlDisplayPicSmall based on the ‘id’ of the model.
When you do
fetchon a collection:and that will
So a
fetchon a collection will remove all the models that are currently in the collection and replace them with brand new model instances. No"change"events will occur, there will only be a single"reset"event.When you do a
fetchon a model:So calling
fetchis pretty much the same loading the data from the server manually and callingsetto change the model.Summary:
Collection#fetchdoesn’t trigger any"change"events, just a"reset"event;Model#fetchwill trigger a"change"event if something changes.If you just want to add a couple new attributes when creating new model instances then you can add new attributes to the incoming JSON using
Model#parse.