View 通常需要一个具有这些属性的对象才能渲染:
{ el: '#someelement', model: someModel }
View 还允许我们将模型的事件绑定(bind)到 View 中的函数:
initialize: function() {
this.model.bind('change', this.renderFromModel, this);
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
renderFromModel: function() {
var t = _.template($('#some-template').html());
$('item-' + this.cid).html(t(this.toJSON()));
return this;
},
问题是我们第一次实例化一个 View 进行渲染时,它期望一个带有 Model 的对象;第二次我们从模型中调用 View 时渲染 View ,它不是。因此,我最终创建了两个 render() 函数。
有没有更好的方法来实现也可以响应 model.change() 事件的单项渲染?
最佳答案
我认为您需要通过调用 underscore.js 的 bindAll 方法来确保您的渲染方法始终绑定(bind) View 。
SomeView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
this.model.bind('change', this.render);
},
render: function(){
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
关于backbone.js - 有没有办法将模型的 .change() 触发器绑定(bind)到 View 的 .render() 函数而不创建多个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7072719/