Chris Dutrow
Chris Dutrow

Reputation: 50362

Backbone - Model that fires an event when a specific attribute is changed

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!

Upvotes: 1

Views: 1500

Answers (2)

Venkat Kotra
Venkat Kotra

Reputation: 10753

Backbone already has an event "change:attribute" that gets fired for each attribute that has changed.

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

Upvotes: 1

Jimmy
Jimmy

Reputation: 37081

You can already bind to attribute-specific change events:

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

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

Upvotes: 2

Related Questions