Retrieving a changed attribute on a change event

Is there a way in this global change event to determine which attribute was changed?

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

I tried the following:

  • Using myModel.previousAttributes() , but it always returns the latest values ​​... I think it is updated only after interacting with the server.
  • Iterate over the gutter attributes and use myModel.hasChanged(attr) , but it always returns false.

Is there any way to do this?

+7
source share
1 answer

You can use model.changedAttributes

changedAttributes model.changedAttributes ([attributes])
Retrieve the hash of only the changed attributes of the model, or false if they are not.
Optionally, a hash of external attributes can be passed in, returning attributes in that hash that are different from the model. This can be used to determine which parts of the view should be updated or what calls need to be made to synchronize changes with 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 the demo http://jsfiddle.net/nikoshr/NYnqM/

+12
source

All Articles