Y
Y
yura_born2021-06-12 18:52:52
JavaScript
yura_born, 2021-06-12 18:52:52

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));
    }
  }


And then I need to delete them, because the page will be re-rendered, I wrote like 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));
    }
  }

But I don’t like something so much, I constantly repeat the announced listeners, and if there are a lot of them .....
Tell me, plz, what is the best and correct way to remove the listeners?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergio, 2021-06-12
@sergiodev

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');

If you are using React, then there is a special ref attribute for this - https://ru.reactjs.org/docs/refs-and-the-dom.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question