Chris
Chris

Reputation: 455

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?

Upvotes: 7

Views: 5128

Answers (3)

Code Commander
Code Commander

Reputation: 17310

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;
}

Upvotes: 4

Chris Dutrow
Chris Dutrow

Reputation: 50402

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');
    }
});

Upvotes: 1

Justin Thomas
Justin Thomas

Reputation: 5848

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

Upvotes: 11

Related Questions