1

What is a good way for a Backbone model to fire a custom event when a specific attribute has been changed?

So far this is the best I've got:

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

Thanks!

4

2 回答 2

2

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

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

  onFooChanged: function () {
    // "foo" property has changed.
  }
});
于 2012-07-22T23:16:03.483 回答
1

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"});
于 2012-07-23T03:12:34.593 回答