它以前被问过好几次,但我所看到和尝试过的,要么不是因为某种原因,要么就是不起作用。
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);
}如有任何帮助,我们将不胜感激。
发布于 2017-11-05 22:11:36
您应该将完全相同的函数传递给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);
};您可能是指callback.bind(this)在setTimeout中的意思,所以我也让自己来解决这个问题:
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);
};https://stackoverflow.com/questions/47127142
复制相似问题