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.
Code is as follows:
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');
}
};
And I run it with
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 for reference: https://codepen.io/tomekbuszewski/pen/LzBZgP?editors=0010
I also tried without the operation
, just writing
if (remove) {
window.removeEventListener('keyup', keyboardFunction);
} else {
window.addEventListener('keyup', keyboardFunction);
}
The result was the same.