Backbone : 监听集合中模型内部集合的 add/remove 事件。

Backbone : listen to add/remove event of a collection inside model in a collection.

我有一组 x(一个实例)模型 y

var y = Backbone.Model.extend({
        defaults: {
            name: null,
            otherCollection: null
        }
    });

otherCollection(多个实例)是模型的集合z

我在集合 x 中监听哪个事件,以便在 otherCollection 中添加/删除任何 z 时我会收到通知?

Backbone 默认仅支持来自 Contained Model --> Containing Collection 的事件传播。如果没有一些额外的努力,它不会进行您正在寻找的那种深层嵌套事件传播。

要从 Contained Collection --> Containing Model 开始,您可以执行如下操作。这里我们设置一个 EpisodeCollection,它将包含在 SeriesModel 中。每当剧集发生变化时,我们都希望在系列中听到它:

var EpisodeCollection = Backbone.Collection.extend({
    comparator: 'id'
    // ... whatever you want
});

var SeriesModel = Backbone.Model.extend({
    initialize: function() {
        if (this.has('episodes')) {
            this.listenTo(this.get('episodes'), 'all', this._onEpisodeChange);
        }
    },

    _onEpisodeChange: function() {
        var eventArgs = Array.prototype.slice.call(arguments, 1);
        var eventName = arguments[0];

        var toTrigger = 'change:episodes:' + eventName + ' change:episodes change';
        this.trigger(toTrigger, eventArgs);
    }    
});

这是一个 运行 JSFiddle,用一个光荣的星球大战例子来说明这一点:

http://jsfiddle.net/9kn6uqdn/4/

您可以想象为需要的更深嵌套建立类似的连接。

Backbone 的一大优点是它不是一个固执己见的框架;它将意见留给应用程序实施者(我们!)。为此,我在几个不同的场合尝试了深度嵌套的事件传播,每次都以不同的方向结束。即使在上面的简单示例中,您也可以看到修改第 6 集的 title 实际上会触发 6 个不同的事件(这可能不是您所期望的)。

您可以付出更多的努力来改进它,但它会很快变得非常复杂。大型应用程序中的事件传播很难推理,所以在我看来,事件流越简单,管理和维护就越容易。

var ModelY = Backbone.Model.extend({});

var ModelZ = Backbone.Model.extend({});

var CollectionX = Backbone.Collection.extend({
    model : ModelY,
    initialize:function(){
    this.listenTo(otherCollection,'add',function(){
            alert('model added to otherCollection');
        });
    }
});

var OtherCollection = Backbone.Collection.extend({ model : ModelZ });


var otherCollection = new OtherCollection();

var collectionX = new CollectionX();

otherCollection.add(new ModelZ());

http://jsfiddle.net/eedfhm7f/

参考资料:http://backbonejs.org/#Events-listenTo