之前已经被问过好几次了,但我见过和尝试过的所有方法要么不是,要么由于某种原因似乎不起作用
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);
}
任何帮助将不胜感激
最佳答案
您应该将完全相同的函数传递给 addEventListener
和 removeEventListener
。
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/