简体   繁体   中英

How can I tell which model changed when listening to the change event of a collection in backbone.js

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/

I should have looked a bit harder.

The object 'this' within the context of the updateShare function in the above example contains an array 'models' which contains all the models in the collection, but the one the fired the change event has property of '_changing: true'.

But the accepted answer is what I was looking for and couldn't find in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM