Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone - Is it possible to bind a change event to a model, except for one property?

I would like a change event to fire anytime I change any property of the model, except for one. Is this possible? Besides doing:

model.bind('change:prop1', func);
model.bind('change:prop2', func);
model.bind('change:prop3', func);
etc....

Or alternatively, is there a way to find out which property triggered the change from within the event handler?

like image 539
Chris Avatar asked Nov 14 '11 19:11

Chris


3 Answers

You could use model.bind('change',function() {/*...*/}) and in the function use hasChanged to check the attributes: if(model.hasChanged('propIWantToExclude')) return;

like image 73
Justin Thomas Avatar answered Nov 14 '22 00:11

Justin Thomas


Justin's answer above will return when 'propIWantToExclude' and some other attributes are changed together. You probably don't want to do that, so you should also look at the size of model.changedAttributes:

if(model.changedAttributes.length == 1 && model.hasChanged('attrIWantToExclude')) {
    return;
}
like image 43
Code Commander Avatar answered Nov 13 '22 23:11

Code Commander


Responding to David Tuite's request to answer the first part of the question, you could set up a function to respond to the "changed" event and then trigger a custom event if the property that you want to ignore was not changed.

This logic would trigger the custom event: 'somePropertyOtherThanThePropIWantToExcludeChanged' if the property was not changed. If multiple properties were changed, including the one you want to ignore, then the custom event would also NOT fire:

model.bind('change', function(){
    if( !model.hasChanged('propIWantToExclude') ){
        model.trigger('somePropertyOtherThanThePropIWantToExcludeChanged');
    }
});
like image 1
Chris Dutrow Avatar answered Nov 13 '22 23:11

Chris Dutrow