RemoveEventListener不起作用
我有一个非常奇怪的案例,使我无法删除eventListener
.这是一个非常简单的功能,可以绑定到键盘事件并在不需要时取消绑定(理论上).
I have this very strange case that prevents me from removing eventListener
. This is a very simple function that binds to keyboard events and unbinds (in theory) when is not needed.
代码如下:
const keyboardEvents = function(input, remove = false) {
const { key, func } = input;
const operation = remove ? 'removeEventListener' : 'addEventListener';
function keyboardFunction(event) {
console.log(event);
if (event.keyCode === key) {
func();
}
}
window[operation]('keyup', keyboardFunction);
if (remove) {
console.log('REMOVED');
} else {
console.log('ADDED');
}
};
然后我用
keyboardEvents({ key: 27, func: testFunc }); // add event
keyboardEvents({ key: 27, func: testFunc }, true); // remove event
问题是,没有删除侦听器.我该怎么办?
Problem is, the listener isn't removed. What can I do?
CodePen供参考: https://codepen.io/tomekbuszewski/pen/LzBZgP ?editors = 0010
CodePen for reference: https://codepen.io/tomekbuszewski/pen/LzBZgP?editors=0010
我也尝试了在没有operation
的情况下,只是编写
I also tried without the operation
, just writing
if (remove) {
window.removeEventListener('keyup', keyboardFunction);
} else {
window.addEventListener('keyup', keyboardFunction);
}
结果是相同的.
您需要提供相同的函数引用,以便从事件处理程序中删除.每次调用keyboardEvents
时,都会创建一个新函数,其名称为
keyboardFunction
,因此呼叫之间存在差异.那么为什么不能删除它.
You need to give the same function reference for removing from the event handler. Every time when you call the keyboardEvents
, you create a new function with name
keyboardFunction
, so there are different from a call to call. So why you can't remove it.
尝试以下代码 代码笔 .
Try this code Codepen.