我有一个问题,我认为是非常基本的东西,但是:
我只看到了集合视图和依赖于正在更新的集合的单个视图的示例。如果您有多个视图试图订阅一个集合事件,例如 reset、addOne、addAll 等,该怎么办?
我是否错过了关于做/不做这件事的一些要点?你有这方面的例子吗?这甚至有意义吗?
任何信息都非常感谢
var Coll = Backbone.Collection.extend({
model: SingleModel,
url: 'service',
initialize: function(){
console.log('collection inited')
}
});
var SingleModel = Backbone.Collection.extend({});
var CollView = Backbone.View.extend({
el: 'ul',
template: Handlebars.compile(someContainerTemplate),
init: function(){
_.bindAll(this, 'render', 'addAll', 'addOne');
this.collection.bind("reset", this.addAll);
this.collection.fetch();
},
render: function(){
$(this.el).append(this.template())
},
addAll: function(){
this.collection.each(this.addOne);
},
addOne: function(model){
var view = new SingleView({ model: model })
}
})
var SingleView = Backbone.View.extend({
tagName: "li",
events: {
"click .delete": "remove"
},
template: Handlebars.compile(someTemplateForSingleItem),
initialize: function() {
_.bindAll(this,'render');
this.model.bind('save', this.addOne);
this.model.bind('destroy', removeEl);
},
remove: function(){
this.model.destroy();
},
removeEl: function(){
$(this.el).remove();
},
render: function() {
var context = this.model.toJSON();
return $(this.el).append(this.template(context));
},
})
// standard so far (excluding any bad practices),
// but what if you have another view dependent on
// say the number of length of the collection, and
// you want it to update if any single models are destroyed
var HeaderView = Backbone.View.extend({
tagName: "div#header",
template: Handlebars.compile(someHeaderTemplate),
initialize: function() {
_.bindAll(this,'render');
this.model.bind('save', this.addOne);
},
render: function() {
//assigning this collection length
var context = this.collection.length;
return $(this.el).append(this.template(context));
},
});
var coll = new Coll();
new CollView({ collection: coll });
new HeaderView({ collection: coll});