add and remove event listener inside function clean js

I have a function that add listeners on a button. And she take some parameters (1,2,3,4,5) others, ... The problem is that the function can be called 20-30 times on page.

function init(num) {
  let vas = (e) => {
    alert(num);
    e.preventDefault();
  }
  document.querySelector("#d22").removeEventListener("click", vas);
  document.querySelector("#d22").addEventListener("click", vas);
}

init(1);
init(2);
init(3);
init(4);

Im learn documentation of event listener, and write some code. It seems that idid everything right? but the event is not deleted, what im do wrong?


Ответы (1 шт):

Автор решения: Ilija Wood

Why first are you trying to remove listener that is created right before that in init-function's scope? Create vas variable in upper scope and reassign it every time in init function, like this:

let vas = null;

function init(num) {
    document.querySelector("#d22").removeEventListener("click", vas);

    vas = (e) => {
        alert(num);
        e.preventDefault();
    };

    document.querySelector("#d22").addEventListener("click", vas);
}

init(1);
init(2);
init(3);
init(4);

In your test case this should help

→ Ссылка