简体   繁体   English

问题与document.removeEventListener()

[英]Problem with document.removeEventListener()

I have a function that creates an event listener: 我有一个创建事件监听器的函数:

document.addEventListener(name, handler.bind(null, name, callback), false);

I use .bind to pass the extra parameters, but when I try to remove it: 我使用.bind传递额外的参数,但是当我尝试删除它时:

document.removeEventListener(name, handler, false);
// or
document.removeEventListener(name, handler.bind(null), false);

It doesn't actual get removed. 实际上并没有被删除。 I have tried various fixes and cannot seem to get it to work. 我已经尝试了各种修复程序,但似乎无法正常工作。

You need to save a reference to the bound function, so that removeEventListener can be called with it later: 您需要保存对绑定函数的引用,以便稍后可以使用removeEventListener对其进行调用:

const boundHandler = handler.bind(null, name, callback);
document.addEventListener(name, boundHandler, false);

// later:

document.removeEventListener(name, boundHandler, false);

The EventTarget.removeEventListener() method removes from the EventTarget an event listener previously registered with EventTarget.addEventListener(). EventTarget.removeEventListener()方法从EventTarget中删除先前向EventTarget.addEventListener()注册的事件侦听器。 The event listener to be removed is identified using a combination of the event type, the event listener function itself , and various optional options that may affect the matching process. 使用事件类型,事件侦听器函数本身以及可能影响匹配过程的各种可选选项的组合来标识要删除的事件侦听器

As you are using Function#bind , The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. 当您使用Function#bindbind()方法创建一个新函数 ,该函数在被调用时将其this关键字设置为提供的值,并在调用新函数时提供给定的参数序列。

Hence while using removeEventListener , you are not passing same reference of the function which was added for addEventListener . 因此,在使用removeEventListener ,您不会传递为addEventListener添加的函数的相同引用。

Have cached Handler function in a variable which could be used for the both, addEventListener as well as removeEventListener 在变量中缓存了Handler function ,该变量可用于addEventListenerremoveEventListener两者

let handlerFunction = handler.bind(null, name, callback);
document.addEventListener(name, handlerFunction, false);
document.removeEventListener(name, handlerFunction, false);

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

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