javascriptdomaddeventlistener

If I add the same anonymous function to an event handler multiple times why will it fire multiple times?


if I add this anonymous => function multiple times, is it really attached multiple times?

I.e. it this assignment statement were called 5 times, would I end up with 5 "copies" of the => listening?

 hintCell.addEventListener("click", () => {
   someCode;
   moreCode;
}

Solution

  • As @Bergi mentioned in the comments:

    If you addEventListener a truly "anonymous" function that has not been stored in a constant or a variable three times, it will be executed three times as a consequence of the event. In contrast to that, a function object, which cannot be called anonymous anymore because it was stored in a constant and therefore has a name (or at least can be called up by a reference) will be executed only once:

    const btn=document.querySelector("button"),
    fn=()=>console.log("only once.");
    for (let i=3; i--;) {
      btn.addEventListener("click",fn);
      btn.addEventListener("click",()=>console.log("THREE times!"));
    }
    <button>click me</button>