Answer the question
In order to leave comments, you need to log in
What is the best way to use removeEventListener?
Hello everyone, I'm setting listeners in the function:
addListeners(): void {
const menuBbtn = document.querySelector('.top-menu');
const btnGarageNext = document.querySelector('#btn-garage-next');
const btnGaragePrev = document.querySelector('#btn-garage-prev');
if (btnGarageNext !== null) {
btnGarageNext.addEventListener('click', this.onButtonGarageNext.bind(this));
}
if (btnGaragePrev !== null) {
btnGaragePrev.addEventListener('click', this.onButtonGaragePrev.bind(this));
}
if (menuBbtn !== null) {
menuBbtn.addEventListener('click', this.onButtonMenu.bind(this));
}
}
removeListeners(): void {
const menuBbtn = document.querySelector('.top-menu');
const btnGarageNext = document.querySelector('#btn-garage-next');
const btnGaragePrev = document.querySelector('#btn-garage-prev');
if (btnGarageNext !== null) {
btnGarageNext.removeEventListener('click', this.onButtonGarageNext);
}
if (btnGaragePrev !== null) {
btnGaragePrev.removeEventListener('click', this.onButtonGaragePrev);
}
if (menuBbtn !== null) {
menuBbtn.addEventListener('click', this.onButtonMenu.bind(this));
}
}
Answer the question
In order to leave comments, you need to log in
In my opinion, listeners are incorrectly removed from you, tk. By binding the method to this via this.onButtonGarageNext.bind(this) you are creating a new function, and in removeEventListener() you are passing the onButtonGarageNext method itself. It turns out that nothing will be deleted, because. such a function is not hung on a click event and the listener will not be found when it is removed.
You need to remember somewhere the function returned from bind() and then pass it to removeEventListener().
As for the repeated code, I would write references to the .top-menu, #btn-garage-next, #btn-garage-prev elements in some class field during initialization, and then reuse them in removeListeners(), for example:
this.menuBbtn = document.querySelector('.top-menu');
this.btnGarageNext = document.querySelector('#btn-garage-next');
this.btnGaragePrev = document.querySelector('#btn-garage-prev');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question