通过添加“改变”我的视图不再绑定到模型的方法了吗?
我仍在尝试了解 Backbone.js 的工作原理。我有一个模型,只要其中一个属性发生更改,我就想运行计算。
window.Print = Backbone.Model.extend({
change: function () {
this.set({ totalTime: this.calculateTime() }, {silent: true});
}
这有效。每当修改属性时,都会触发“change”方法并完成计算。
问题是,有了“更改”方法,我的视图不再重新呈现更改(我假设它不再绑定到更改方法?)。如果我把它拿出来,我的观点就会按预期工作。
我的观点如下:
window.TimeView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.template = _.template($('#template').html());
},
render: function(){
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
我有一种感觉,我正在错误地处理这个问题......我的计算不应该在模型内完成吗?应该在哪里做? (Backbone是我第一次尝试实现MVC)
编辑: 我想通了。我应该绑定代码来更改,而不是覆盖它。
window.Print = Backbone.Model.extend({
initialize: function() {
this.bind('change', function() {
this.set({ totalTime: this.calculateTime() }, {silent: true});
});
}
});
I am still trying to wrap my head around how Backbone.js works. I have a Model that I want to run a calculation whenever one of the attributes is changed.
window.Print = Backbone.Model.extend({
change: function () {
this.set({ totalTime: this.calculateTime() }, {silent: true});
}
Which works. Whenever an attribute is modified, the "change" method fires and the calculation is done.
The problem is that having the "change" method in there, my view no longer re-renders on a change (I am assuming it no longer is bound to the change method?). If I take it out, my view works as expected.
My view looks like this:
window.TimeView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.template = _.template($('#template').html());
},
render: function(){
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
I have a feeling I am approaching this incorrectly... Should my calculation not be done within the Model? Where should it be done? (Backbone is the first time I have tried to implement MVC)
EDIT:
I figured it out. I should be binding the code to change, not overwriting it.
window.Print = Backbone.Model.extend({
initialize: function() {
this.bind('change', function() {
this.set({ totalTime: this.calculateTime() }, {silent: true});
});
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想通了。我正在覆盖渲染方法,我发现有效的方法是在初始化函数时将我想要的操作绑定到该方法。
I figured it out. I was overwriting the render method, the way I found that works is to bind the actions I wanted to the method when I initialize the function.