I want to add and event listener, I want the function the event listener calls to be bound to the calling scope and I want to be able to remove the listener at some arbitrary date in the future.
The obvious thing doesn't work:
function Thing(){
this.thingINeed = "important!"
}
// the function that does the thing.
Thing.prototype.handlerFunction = function(e){
console.log(this.thingINeed)
e.preventDefault;
}
// do the binding.
window.document.body.addEventListener('click', this.handlerFunction.bind());
// sometime later...this is my best guess. The event listener remains active.
window.removeEventListener('click', this.handlerFunction.bind());
// this also doesn't work:
window.removeEventListener('click', this.handlerFunction);
So I flogged together some code that does work:
function Thing(){
this.thingINeed = "important!"
}
Thing.prototype.handlerFunction = function(e){
console.log(this.thingINeed);
e.preventDefault;
}
// Where the 'magic' happens...
this.boundHandlerFunction = this.handlerFunction.bind(this);
window.document.body.addEventListener('click', this.boundHandlerFunction);
// sometime later...
window.removeEventListener('click', this.boundHandlerFunction);
MDN goes into some detail on matching event listeners with removal, but it doesn't mention .bind()
and I can't find any examples of other people doing it this way. The code isn't exactly obvious without extensive commenting.
Is there a better way?
jQuery event listeners can be named, which makes them really easy to remove, but that isn't possible with vanilla?
Thanks.