Reputation: 13
It's been asked several times before, but all the one's I've seen and tried either aren't it, or don't seem to work for some reason
onEnter takes a callback that it will fire whenever the enter key is pressed (that much works), but when I try calling removeEventListener()
, it doesn't seem to work. I've tried making the function a variable instead of a declaration, I've tried setting the useCapture
flags for both adding/removing, and I've tried all combinations of trying to .bind(this)
to either the function arguments or the function itself, and also putting the removeEventListener()
line in different places (before/after the setTimeout()
), but to no avail. The event listeners either persist (and accumulate on the div
) or don't seem to get added at all in some tries
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);
}
Any help would be hella appreciated
Upvotes: 0
Views: 1269
Reputation: 1429
You should pass exactly the same function to both addEventListener
and 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);
};
In fact an arrow function would be a better option here since it does not have its own this
.
And you probably meant callback.bind(this)
in the setTimeout
so I let myself to fix that as well:
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);
};
Upvotes: 2