javascript - 删除事件监听器不起作用?

标签 javascript addeventlistener event-listener

之前已经被问过好几次了,但我见过和尝试过的所有方法要么不是,要么由于某种原因似乎不起作用

onEnter 接受一个回调,只要按下 Enter 键,它就会触发(这很有效),但是当我尝试调用 removeEventListener() 时,它似乎不起作用。我尝试过将函数设置为变量而不是声明,我尝试过为添加/删除设置 useCapture 标志,并且我尝试过尝试 .bind 的所有组合(this) 到函数参数或函数本身,并将 removeEventListener() 行放在不同的位置(在 setTimeout() 之前/之后) ),但无济于事。事件监听器要么持续存在(并累积在 div 上),要么在某些尝试中根本没有添加

MyConsole.prototype.onEnter = function(callback) {
    const callCallback = function(e) {
        e.preventDefault();
        if (e.keyCode === 13 && typeof callback === "function") {
            setTimeout(function () {
                callback();
            }.bind(this), 0);
            this.textAreaInputDiv.removeEventListener("keyup", callCallback.bind(this), true);
        }
    }
    this.textAreaInputDiv.addEventListener("keyup", callCallback.bind(this), true);
}

任何帮助将不胜感激

最佳答案

您应该将完全相同的函数传递给 addEventListenerremoveEventListener

MyConsole.prototype.onEnter = function(callback) {
    const callCallback = function(e) {
        e.preventDefault();
        if (e.keyCode === 13 && typeof callback === "function") {
            setTimeout(function () {
                callback();
            }.bind(this), 0);
            this.textAreaInputDiv.removeEventListener("keyup", callCallbackBound, true);
        }
    };

    const callCallbackBound = callCallback.bind(this);

    this.textAreaInputDiv.addEventListener("keyup", callCallbackBound, true);
};

事实上是arrow function在这里将是一个更好的选择,因为 it does not have its own this .

你可能指的是setTimeout中的callback.bind(this),所以我也让自己修复这个问题:

MyConsole.prototype.onEnter = function(callback) {
    const callCallback = (e) => {
        e.preventDefault();
        if (e.keyCode === 13 && typeof callback === "function") {
            setTimeout(callback.bind(this), 0);
            this.textAreaInputDiv.removeEventListener("keyup", callCallback, true);
        }
    };

    this.textAreaInputDiv.addEventListener("keyup", callCallback, true);
};

关于javascript - 删除事件监听器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47127142/

相关文章:

java - 当我删除字段时,Firestore EventListener 导致 Null 异常

Javascript在foreach循环中添加事件监听器只有最后一个条目有效

javascript - 如何使 google recaptcha 响应宽度为 100%

javascript - 删除 JSON 的特定部分

javascript - 如何使用 async/await 方法将对象传递到 phantom js 页面?

javascript - 如何在 Javascript 中使用 eventListener 进行重置

javascript - 获取更改前 contenteditable 元素的 textContent(或 `beforeinput` )

javascript - 使用 Javascript API 将行添加到 Excel 中的现有表

javascript - 重新启用网页右键: "Void document oncontextmenu null" trick not working

design-patterns - EventListener 是 Observable 吗?