简体   繁体   中英

RemoveEventListener doesn't work

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.

You need to give the same function reference for removing from the event handler. Every time when you call the keyboardEvents , you create a new function with name keyboardFunction , so there are different from a call to call. So why you can't remove it.

Try this code Codepen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM