[英]Preventing function from being invoked twice when binding in Backbone?
当我的Backbone模型中的两个属性(“a”或“b”)中的任何一个发生变化时,我想计算第三个属性“c”:
initialize: function() {
this.bind("change:a", this.calculateC);
this.bind("change:b", this.calculateC);
},
calculateC: function() {
this.attributes.c = ...
}
如果同时在模型上同时设置a和b,那么防止c被计算两次的好方法是什么?
这些属性不会同时设置,它们将在一次设置,因此您需要查看这两个事件。 相关代码如下所示 :
// Set a hash of model attributes on the object, firing `"change"` unless you
// choose to silence it.
set : function(attrs, options) {
// ...
// Update attributes.
for (var attr in attrs) {
var val = attrs[attr];
if (!_.isEqual(now[attr], val)) {
now[attr] = val;
// ...
if (!options.silent) this.trigger('change:' + attr, this, val, options);
}
}
// Fire the `"change"` event, if the model has been changed.
if (!alreadyChanging && !options.silent && this._changed) this.change(options);
您可以看到设置了其中一个属性,然后触发了其更改事件,然后为下一个属性重复该过程。 如果您只想要一个事件,那么您应该只绑定整个模型的更改事件。
为了完整起见,我应该提到Model#set
的接口文档没有指定何时触发单个更改事件的任何特定行为,它只表示它们将被触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.