如何断开主干集合,使每个子集合也注册到将由父集合注册的所有事件

how to break backbone collection such that each of the child collection also register to all the events that will be registered by parent collection

本文关键字:集合 注册 事件 子集合 断开 何断开      更新时间:2024-05-25

我想分解一个主干集合,以便每个子集合也注册到将由父集合注册的事件。

例如,我有收集

parent = {
models : [model1, model2, model3, model4, model5 ]
//other properties of collections
}

插入按特定属性(如"a")分组的子对象

child1 = {
models : [model1, model2, model4],
//other properties of collection
}
child2 = {
models : [model3, model5],
//other properties of collection
}

附言:子集合的数量并不具体。这些都是动态创建的。

现在,每当父集合上发生任何事件(自定义或预定义)时,我都想要。所有子集合也应注册这些事件。

有什么合适的方法吗?

您要完成的任务有几部分。首先,您希望在子集合上触发的任何事件都能执行某些操作;为了实现这一点,您可以使用特殊的"所有"事件绑定:

var ChildCollection = Backbone.Extend({
    initialize: function() {
        this.on('all', this.handleEvent);
    },
    handleEvent: function() {
        // do something
    }
});

接下来,你想让你的孩子收藏了解他们的父母,你可以使用一个选项:

initialize: function(options) {
    this.parent = options.parent;
    this.on('all', this.handleEvent);
},

然后在创建新的子集合时传入该选项:

var parent=new Backbone.Collection();var child1=新的ChildCollection([model1,model2,model4],{parent:parent});

最后,您希望在父级上触发事件:

handleEvent: function(e) {
    this.parent.trigger.apply(this, arguments);
}

希望能有所帮助。