2012-07-22 169 views
1

當特定屬性發生更改時,骨幹模型發起自定義事件的好方法是什麼?骨幹 - 在特定屬性發生更改時觸發事件的模型

到目前爲止,這是我已經得到了最好:

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"); 
     } 
    } 
}) 

謝謝!

回答

2

您已經可以綁定到特定的屬性變更事件:

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

    onFooChanged: function() { 
    // "foo" property has changed. 
    } 
}); 
+0

啊,很好。謝謝! – 2012-07-22 23:33:30

1

骨幹已經有一個事件「的變化:屬性」是獲取已更改每個屬性解僱。

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"}); 
相關問題