I am trying to figure out how best to remove anonymous event handlers using jQuery.
I define a variable to store the jQuery object:
var dom = $('#private-module');
Later 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 that my understanding of scale here is erroneous. What is the preferred way to remove the handler in this situation? I tried namespacing events and all kinds, but no luck, so I guess it's just that I forgot. Perhaps I should not even use anonymous functions for event handlers.
Just to say something about 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();
});
.one. .