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;
}
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;
}
Share
Improve this question
edited Mar 26 at 2:51
Clay Nichols
asked Mar 18 at 19:22
Clay NicholsClay Nichols
12.2k30 gold badges114 silver badges179 bronze badges
5
|
2 Answers
Reset to default 1As @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>
I think if you add the same function, that is, the same anonymous function multiple times to an event listener, it gets attached multiple times and will run multiple times, because everytime you call.
hintCell.addEventListener("click", () => {
sameCode;
moreCode;
);
you are bascically creating a new anonymous function and adding it to a separate listerner, and i don't think the browser has a way of knowing that it's the same function because the function is basically a different object in memory. hope this helps.
addEventListener
with the same function multiple times, that one function is only registered once (and will be removed on the first call toremoveEventListener
with the same function as an argument). It's really the object identity that matters. – Bergi Commented Mar 18 at 20:47