【问题标题】:Preventing function from being invoked twice when binding in Backbone?在Backbone中绑定时防止函数被调用两次?
【发布时间】:2011-12-13 21:25:31
【问题描述】:

当我的 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 被计算两次?

【问题讨论】:

    标签: javascript binding backbone.js


    【解决方案1】:

    属性不会同时设置,它们将一次设置一个,因此您需要查看这两个事件。 relevant code looks like this

    // 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 的界面文档没有指定任何特定的行为,即何时触发各个更改事件,它只是说它们将被触发。

    【讨论】:

    • 好的,所以你建议这样做 this.bind("change", this.calculateC) 然后检查 if ("a" or "b" in changedAttributes)?谢谢。 /D
    • @dani:我建议你绑定到change:achange:b 而不必担心。您的意图是知道ab 何时更改,以便绑定到各个事件与您尝试执行的操作完全匹配。如果您的计算非常昂贵,那么仅绑定到整个 change 事件是有意义的,但您最好不要太担心优化某些东西,直到您知道这是一个问题。
    • 好的,谢谢。我倾向于过早地优化......我会按照你说的那样保留它,因为它至少在逻辑上是准确的......
    • @dani:优化正确的代码比纠正优化的代码容易得多:)
    猜你喜欢
    • 2019-03-03
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多