最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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
  • 1 Yes, every time you call addEventListener on an element, it's adding a new listener. – nbokmans Commented Mar 18 at 19:25
  • 2 What happened when you tried it? – mykaf Commented Mar 18 at 19:39
  • 2 @nbokmans Actually, no. If you call addEventListener with the same function multiple times, that one function is only registered once (and will be removed on the first call to removeEventListener with the same function as an argument). It's really the object identity that matters. – Bergi Commented Mar 18 at 20:47
  • What's with the down votes? – Clay Nichols Commented Mar 26 at 2:46
  • 1 @ClayNichols I guess you could have gotten the answer by just running the code – Bergi Commented Mar 26 at 3:00
Add a comment  | 

2 Answers 2

Reset to default 1

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>

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论