防止函数在主干中绑定时被调用两次



当我的主干模型中的两个属性("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);

您可以看到设置了其中一个属性,然后触发其更改事件,然后对下一个属性重复该过程。如果你只想要一个事件,那么你应该只绑定到整个模型的change事件。

为了完整起见,我应该提到Model#set的接口文档并没有指定任何特定的行为,关于何时触发单个更改事件,它只是说它们将被触发。

最新更新