7

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?

jviotti
  • 17,881
  • 26
  • 89
  • 148

1 Answers1

12

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/

nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • 1
    I may be late to the party. If you are using Backbone 0.9.9 and above start using .listenTo instead of .on so that you don't end up with objects that are immune to garbage collection. – Ananda Aug 06 '16 at 16:47