我有 4 个模型实例。为什么渲染函数会触发四次?我希望它只渲染一次(并循环遍历每个模型并触发 Handlebars 模板)。在前端,如果我有四个模型实例,我将获得 16 个模板。如果我用错误的术语来描述它,我深表歉意。我是菜鸟。
define(['handlebars', 'text!event-template'],
function(Handlebars, EventTemplate) {
var EventView = Backbone.View.extend({
el: $('#event-list')[0],
initialize: function(collection) {
this.collection = collection;
this.listenTo(this.collection, 'add', this.render);
console.log('View Event : Initialized');
},
render : function() {
var _el = this.$el; //refrencing the el: above
_.each(this.collection.models, function(model) {
var template = Handlebars.default.compile($(EventTemplate).html());
_el.append(template(model.attributes));
});
console.log('rendering');
}
});
return EventView;
}
);
最佳答案
当集契约(Contract)步时,它会为添加到集合中的每个模型触发add
。如果你想绑定(bind)到add
,我通常做的是创建一个名为“append”的方法来将单个模型添加到 View 中。 add
事件将遍历集合,因此您不需要在 View 上使用“循环”来保持 View 的干净,并且在添加到集合和添加之间更多的是一对一的关系到 View 。所以我会将你的代码更改为这样
define(['handlebars', 'text!event-template'],
function(Handlebars, EventTemplate) {
var EventView = Backbone.View.extend({
el: $('#event-list')[0],
initialize: function(collection) {
this.collection = collection;
this.listenTo(this.collection, 'add', this.append);
console.log('View Event : Initialized');
},
append: function( model ) {
var _el = this.$el; //refrencing the el: above
var template = Handlebars.default.compile($(EventTemplate).html());
_el.append(template(model.attributes));
console.log('adding');
}
});
return EventView;
}
);
这是一个很好的实现。之后,如果您将一个模型自动“添加”到集合中,它将立即显示在 DOM 中。
关于javascript - Backbone : Render function fires for each instance of model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23478996/