简体   繁体   English

无法删除我附加的事件监听器

[英]can't remove an event listener I attached

I have attached an event listener in a module using 我在一个模块中附加了一个事件监听器

document.addEventListener('keydown', () => this.clickCatcherFunction(target_id));

but when that function is executed, the line 但是当执行该功能时,该行

document.removeEventListener("keydown", () => this.clickCatcherFunction());

doesn't remove the listener. 不会删除侦听器。 Next time a key is pressed it executes the clickCatcherFunction and fails. 下次按下一个键时,它会执行clickCatcherFunction并失败。 How can I pass it the same function I used to create it to remove it? 我如何传递它与我用来创建它以删除它的相同功能?

other failed attempts: 其他失败的尝试:

document.removeEventListener("keydown", this.clickCatcherFunction());
document.removeEventListener("keydown", clickCatcherFunction());
document.removeEventListener("keydown", clickCatcherFunction);

Only named functions can be removed, not anonymous functions because even if you make an identical anonymous function, it won't be the exact same instance of the function you had previously added. 只有命名功能,可以删除,而不是匿名功能,因为即使你作出相同的匿名函数,它不会是你以前添加的功能完全相同的实例 You'll have to set up your function separately, like this: 你必须单独设置你的功能,如下所示:

function clickCather(evt){
  .  .  .
}

Then you can add and remove it with addEventListener("click", clickCatcher) and removeEventListener("click", clickCatcher); 然后你可以使用addEventListener("click", clickCatcher)removeEventListener("click", clickCatcher);添加和删​​除它removeEventListener("click", clickCatcher); because you'll be referring to the same function instance in memory. 因为你将在内存中引用相同的函数实例。

And, note that with both addEventListener and removeEventListener you don't invoke your function (no parenthesis at the end of the function name), you only want to refer to it. 并且,请注意,使用addEventListenerremoveEventListener都不会调用函数(函数名末尾没有括号),您只想引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM