Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting changed attribute on change event

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?

like image 525
jviotti Avatar asked May 24 '13 12:05

jviotti


1 Answers

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/

like image 170
nikoshr Avatar answered Nov 11 '22 09:11

nikoshr