我有代表树的集合。每个模型都有父属性,从服务器变为id。在使用传入数据重置收集后,每个模型必须在集合中查找其父级并将引用设置为属性而不是普通ID。之后,必须有一个从集合触发的事件,它已准备好渲染。
var node = Backbone.Model.extend({
initialize: function(){
//reset event fired after all models are in collection,
//so we can setup relations
this.collection.on('reset', this.setup, this);
},
setup: function(){
this.set('parent', this.collection.get(this.get('parent')));
this.trigger('ready', this);//-->to collection event aggregator?
}
});
var tree = Backbone.Collection.extend({model: node})
是否有任何干净的方式来查看所有模型的设置?或者我必须在集合中编写自定义事件聚合器?
答案 0 :(得分:0)
实际上,您想要的是在reset
而不是Collection
中绑定Model
事件。
var Node = Backbone.Model.extend({
}),
Tree = Backbone.Collection.extend({
model: Node,
initialize: function() {
this.on('reset', this.setup, this);
},
setup: function() {
this.each(this.updateModel, this);
//Here you have all your models setup
},
updateModel: function(m) {
m.set({
parent: this.get(m.get('parent'));
});
}
})