I have some Backbone.js code that bind a click event to a button, and I want to unbind it after clicked, the code sample as below:
var AppView = Backbone.View.extend({
el:$("#app-view"),
initialize:function(){
_.bindAll(this,"cancel");
},
events:{
"click .button":"cancel"
},
cancel:function(){
console.log("do something...");
this.$(".button").unbind("click");
}
});
var view = new AppView();
However the unbind is not working, I tried several different way and end up binding event in initialize function with jQuery but not in Backbone.events model.
Anyone know why the unbind is not working?
The reason it doesn't work is that Backbonejs doesn't bind the event on the DOM Element .button itself. It delegates the event like this:
(docs: http://api.jquery.com/delegate)
You have to undelegate the event like this:
(docs: http://api.jquery.com/undelegate)
So your code should look like:
Another (maybe better) way to solve this is to create a state attribute like
this.isCancelable
now everytime thecancel
function is called you check ifthis.isCancelable
is set to true, if yes you proceed your action and setthis.isCancelable
to false.Another button could reactivate the cancel button by setting
this.isCancelable
to true without binding/unbinding the click event.You could solve this another way
underscore.js once function ensures that the wrapped function can only be called once.
There is an even easier way, assuming you want to undelegate all events:
you can simply use object.off, the code below is work for me
I like bradgonesurfing answer. However I came across a problem using the _.once approach when multiple instances of the View are created. Namely that _.once would restrict the function to be called only once for all objects of that type i.e. the restriction was at the class level rather than instance level.
I handled the problem this way:
Hopefully this will help someone