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:
myModel.previousAttributes()
but it always returned latest values... I guess it only updates after a server interaction.myModel.hasChanged(attr)
but it always returned false.It's there a way to accomplish this?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With