【问题标题】:Backbone - Model that fires an event when a specific attribute is changedBackbone - 特定属性更改时触发事件的模型
【发布时间】:2012-07-22 22:36:58
【问题描述】:

当特定属性发生更改时,Backbone 模型触发自定义事件的好方法是什么?

到目前为止,这是我所拥有的最好的:

var model = Backbone.Model.extend({
    initialize: function(){
        // Bind the mode's "change" event to a custom function on itself called "customChanged"
        this.on('change', this.customChanged);
    },
    // Custom function that fires when the "change" event fires 
    customChanged: function(){
        // Fire this custom event if the specific attribute has been changed
        if( this.hasChanged("a_specific_attribute")  ){
            this.trigger("change_the_specific_attribute");
        }
    }
})

谢谢!

【问题讨论】:

    标签: javascript backbone.js backbone-events


    【解决方案1】:

    您已经可以绑定到特定于属性的更改事件:

    var model = Backbone.Model.extend({
      initialize: function () {
        this.on("change:foo", this.onFooChanged);
      },
    
      onFooChanged: function () {
        // "foo" property has changed.
      }
    });
    

    【讨论】:

      【解决方案2】:

      Backbone 已经有一个事件“change:attribute”,该事件会针对每个已更改的属性触发。

      var bill = new Backbone.Model({
            name: "Bill Smith"
          });
      
          bill.on("change:name", function(model, name) {
            alert("Changed name to " + name);
          });
      
          bill.set({name : "Bill Jones"});
      

      【讨论】:

        猜你喜欢
        • 2023-03-07
        • 2011-06-01
        • 1970-01-01
        • 2012-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-08
        相关资源
        最近更新 更多