RemoveEventListener不起作用 [英] RemoveEventListener doesn't work

查看:1153
本文介绍了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.

这篇关于RemoveEventListener不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆