Ian Hunter
Ian Hunter

Reputation: 9774

Prevent single attribute from firing this.bind("change")

In Backbone.js, I have a model I am binding a change event to, but I want to prevent this from happening on specific attribute changes. For example, I want it to fire for every single time model.set() is called, except when calling model.set({arbitraryName: value}).

Here's what I have:

this.bind("change", function() {
  this.update();
});

But I have no clue how to determine what is being set--any ideas?

EDIT

It looks like I can call

model.set({arbitraryName: value}, {silent: true}) 

to prevent the change event from firing (which works for what I need), but what if I have something bound like:

this.bind("change:arbitraryName", functionName)

Upvotes: 1

Views: 403

Answers (1)

idbentley
idbentley

Reputation: 4218

You can consider using hasChanged in the event handler?

var self = this;
this.bind("change", function() {
    if(!self.hasChanged("someAttribute")){
        self.update();
    }
});

I'm not sure I understand your question completely. Please notice the difference of the above, and the below.

this.bind("change:someAttribute", function(){
    self.update();
});

The first one will fire update on any change where someAttribute remains constant. The second one will fire update on any change to someAttribute.

Hope this helps.

Upvotes: 3

Related Questions