admin管理员组文章数量:1346287
Assume a Backbone model with the following attributes: - subtotal - discount - total
Whenever a change is made to discount, the total needs to be updated and I'd like the model to care of this.
I have tried binding an update method (defined in the model) to the model's change event (in the model's initialize method) so that with each change event, the model would update the total attribute, but this does not seem to work.
var Cost = Backbone.Model.extend({
initialize : function() {
this.bind('change', this.update);
},
update : function() {
// UPDATE LOGIC
}
});
What is the best approach to have the model fire a method (of its own) when it triggers a change event?
Assume a Backbone model with the following attributes: - subtotal - discount - total
Whenever a change is made to discount, the total needs to be updated and I'd like the model to care of this.
I have tried binding an update method (defined in the model) to the model's change event (in the model's initialize method) so that with each change event, the model would update the total attribute, but this does not seem to work.
var Cost = Backbone.Model.extend({
initialize : function() {
this.bind('change', this.update);
},
update : function() {
// UPDATE LOGIC
}
});
What is the best approach to have the model fire a method (of its own) when it triggers a change event?
Share Improve this question asked Dec 8, 2011 at 16:19 Bart JacobsBart Jacobs 9,0827 gold badges49 silver badges89 bronze badges1 Answer
Reset to default 9Do you use the set
method of the model? This bit of code calls update when discount
is changed:
var Cost = Backbone.Model.extend({
defaults: {
subtotal: 0,
discount: 0,
total: 0
},
initialize: function () {
_.bindAll(this, "update");
this.on('change:discount', this.update);
// or, for all attributes
// this.on('change', this.update);
},
update: function () {
console.log("update : "+this.get("discount"))
}
});
var c = new Cost();
c.set({discount: 10});
本文标签: javascriptBackbone Update model after change eventStack Overflow
版权声明:本文标题:javascript - Backbone: Update model after change event - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743825311a2545530.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论