How to know which model changed when listening to the event changes a collection in backbone.js

advertisements

I have created two collections in backbone and I want to bind the first collection to a model change event from the second collection.

    var ProjectUserList = Backbone.Collection.extend({

        model: app.projectUser,
        url: config.base + 'api/project/project_users'

    });

    //instantiate
    app.projectUserList = new ProjectUserList();

Second collection with bound change event from first:

    var FileList = Backbone.Collection.extend({

        initialize: function () {
            app.projectUserList.on('change', this.updateShare);
        },

        updateShare: function () {
            console.log(this);
        }
    });

How do I know which model has changed in the collection?


From the fine manual:

Catalog of Events

Here's a list of all of the built-in events that Backbone.js can fire. You're also free to trigger your own events on Models and Views as you see fit.

  • [...]
  • "change" (model, options) — when a model's attributes have changed.

So the first argument to the "change" event handler will be the model that originally triggered the event.

For example, given a simple set up like this:

var M = Backbone.Model.extend({});
var C = Backbone.Collection.extend({
    model: M
});
var c = new C([
    { id: 1, s: 'where' },
    { id: 2, s: 'is' },
    { id: 3, s: 'pancakes' },
    { id: 4, s: 'house' }
]);
c.on('change', function(model, options) { /*...*/ });
c.at(​​​​​​​​​​​​​​​​​3).set('s', 'house?');​​​​​​​​​​

The model argument for the "change" handler will be the one wrapping { id: 4, ... }.

Demo: http://jsfiddle.net/ambiguous/aE2XE/