Getting changed attribute on change event

jviotti picture jviotti · May 24, 2013 · Viewed 8k times · Source

In this global change event, is there a way I can detect which attribute was changed?

myModel.on('change', function(model) {
  // Which attribute changed?
});

I tried the following:

  • Using myModel.previousAttributes() but it always returned latest values... I guess it only updates after a server interaction.
  • Iterating trough attributes and using myModel.hasChanged(attr) but it always returned false.

It's there a way to accomplish this?

Answer

nikoshr picture nikoshr · May 24, 2013

You can use model.changedAttributes

changedAttributes model.changedAttributes([attributes])
Retrieve a hash of only the model's attributes that have changed, or false if there are none.
Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server

For example,

var m = new Backbone.Model({
    att1: 'a',
    att2: 'b',
    att3: 'c'
});

m.on('change', function() {
    console.log(m.changedAttributes());
    console.log(_.keys(m.changedAttributes()));
});

m.set({
    att1: 'd',
    att3: 'e'
});

And a demo http://jsfiddle.net/nikoshr/NYnqM/