I am trying to conditionally add and remove event listeners on a button when the window is resized. To be able to remove the event listener, it has to be a named function.
The problem is it messes with this
context, and therefore this.element
in my handle()
function is not accessible.
I can bind this
and pass it along:
this.button.addEventListener('click', this.handle.bind(this));
But then it does not get removed, as it appears to not be the same event listener. Can i pass this
differently, or is there some other way to remove event listeners? I have tried to clone the element and replace it, but then the event listener does not get reattached.
As per here: How to remove all listeners in an element?
Here is some simplified code:
export default class Classname {
constructor(element, button) {
this.button = button;
this.element = document.querySelector(element);
this.resize();
}
handle() {
// do stuff
console.log(this.element);
}
clickEvents() {
if (condition) {
this.button.addEventListener('click', this.handle);
} else {
this.button.removeEventListener('click', this.handle);
}
}
resize() {
window.addEventListener('resize', () => {
this.clickEvents();
})
}
}