Question

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.

Was it helpful?

Solution

When you do fetch on a collection:

the collection will reset

and that will

replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end. [...] Using reset with no arguments is useful as a way to empty the collection.

So a fetch on 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 fetch on a model:

A "change" event will be triggered if the server's state differs from the current attributes.

So calling fetch is pretty much the same loading the data from the server manually and calling set to change the model.


Summary: Collection#fetch doesn't trigger any "change" events, just a "reset" event; Model#fetch will 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top