我有一个从集合中呈现自己的 View :
render: function() {
$(this.el).html(JST['templates/menu']({collection: this.collection }));
$('#nav').html(this.el);
}
在 View 初始化程序中,我将集合的添加事件绑定(bind)到 View 的渲染函数上:
initialize: function() {
this.render();
var self = this;
this.collection.bind("add", function(event){
self.render();
});
}
在应用程序的其他地方,我将一个项目添加到集合中。
bookSubscription_collection.add(model);
该代码的问题是,如果我向集合中添加一个新项目,那么集合中的所有项目都会重新呈现。
有没有办法在不重新渲染所有其他项目的情况下将新项目添加到集合中,而只需渲染新项目?
最佳答案
这是我如何做的简化版本。 reset
将所有模型添加到 UI 和 add
将单个模型添加到 UI。 addAll
基本上有一个循环调用 addOne
对于每个模型。它可能可以进行更好的优化,但效果很好。
initialize: function() {
_.bindAll(this, 'render', 'addOne', 'addAll');
leads.bind('add', this.addOne, this);
leads.bind('reset', this.addAll, this);
},
render: function() {
this.addAll();
return this;
},
addOne: function(model) {
// add the model to HTML
},
addAll: function(options) {
leads.each(this.addOne);
return this;
}
关于collections - Backbone .js:将元素添加到集合而不重新渲染所有集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9287244/