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?
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 differentevents
hash, all callbacks are removed and delegated afresh — useful for views which need to behave differently when in different modes.
Note two things:
events
object to delegateEvents
, it will use this.events
by default but you can use different events if you want to.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).