简体   繁体   English

在backbone.js中收听集合的change事件时,如何判断哪个模型发生了变化

[英]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. 这是Backbone.js可以触发的所有内置事件的列表。 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. 因此, "change"事件处理程序的第一个参数将是最初触发事件的模型。

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, ... } . "change"处理程序的model参数将是包装{ id: 4, ... }model参数。

Demo: http://jsfiddle.net/ambiguous/aE2XE/ 演示: 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'. 上面示例中updateShare函数上下文中的对象'this'包含一个数组'models',其中包含集合中的所有模型,但触发change事件的对象具有'_changing:true'属性。

But the accepted answer is what I was looking for and couldn't find in the documentation. 但是接受的答案是我在寻找并且在文档中找不到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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