Question

I have a Backbone.View which has the following events:

...

events : {
    "click .text1" : "doSomething",
    "click .text2" : "doAnotherThing",
},

...

I need to undelegate the second event. I know you can use this.undelegateEvents(); but it undelegates all the events on the view. I need to undelegate only one event. How can I do it?

Was it helpful?

Solution

From the fine manual:

delegateEvents delegateEvents([events])

Uses jQuery's on function to provide declarative callbacks for DOM events within a view.
[...]
When delegateEvents is run again, perhaps with a different events hash, all callbacks are removed and delegated afresh — useful for views which need to behave differently when in different modes.

Note two things:

  1. You can pass an events object to delegateEvents, it will use this.events by default but you can use different events if you want to.
  2. Calling delegateEvents will, more or less, call undelegateEvents before binding the new ones.

Putting those together gives us:

this.delegateEvents(
    _(this.events).omit('click .text2')
);

as an easy way to remove the single event handler that you want to get rid of. BTW, _.omit just gives you a copy of an object with certain keys left out so _(this.events).omit('click .text2') can be used to get the event bindings you're interested in without altering this.events (which is attached to the prototype and so shared by all current and future instances of your view).

Demo: http://jsfiddle.net/ambiguous/T6ncT/

OTHER TIPS

From the backbone docs:

A single-event version of delegateEvents is available as delegate. In fact, delegateEvents is simply a multi-event wrapper around delegate. A counterpart to undelegateEvents is available as undelegate.

The function from the source code is:

undelegate: function(eventName, selector, listener) {
  this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
  return this;
}

So call this.undelegate("click",".text2").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top