I'm trying to figure out how best to remove anonymous event handlers using jQuery.
I define a variable to hold my jQuery object:
var dom = $('#private-module');
Later on in my object:
run: function () {
var button, that = this;
button = dom.append('<button class="btn">Click Me</button>');
button.on('click', function(event) {
console.log('Clicked!');
that.destroy();
});
},
destroy: function () {
var button;
button = dom.find('.btn');
button.off('click');
}
No matter what I do, I cannot kill the click handler on the button. Feels like my understanding here of scope is flawed. What is the preferred way, in this situation to remove the handler? I've tried namespacing the events and all sorts but no luck so I am guessing it's something simple that I've overlooked. Perhaps I shouldn't even be using anonymous functions for event handlers.
Just to bolt something on to my reasoning for using .append:
http://jsperf.com/jquery-append-vs-appendto
Here is the final solution:
dom.append('<button class="btn">Send Message</button>');
button = dom.find('.btn');
button.on('click', function (event) {
sendTestMessage();
that.destroy();
});
I also agree and understand about using the .one method. Thanks for that.
button = dom.append('<button class="btn">Click Me</button>');
returns the dom, not the button, so you bound the event handler on the dom
.
Change to:
button = $('<button class="btn">Click Me</button>').appendTo(dom);
And here is the working demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With