javascriptaddeventlistenerevent-listenerkeydownremoveeventlistener

Trying to removeEventListener but its not working. Javascript


I am trying to remove this event listener that I added and it doesn't remove. I'm not sure what I am doing wrong. Any thoughts is greatly appreciated? My code is below.

headerElement.addEventListener('keydown', (evt) => onHeaderKeyDown(parentElement, columnApi, evt));
headerElement.removeEventListener('keydown', (evt) => onHeaderKeyDown(parentElement, columnApi, evt));

Solution

  • When you

    headerElement.addEventListener('keydown', 
      (evt) => onHeaderKeyDown(parentElement, columnApi, evt));
    headerElement.removeEventListener('keydown', 
      (evt) => onHeaderKeyDown(parentElement, columnApi, evt));
    

    you're actually creating two handlers.

    ((evt) => doSomething()) === ((evt) => doSomething()) is false. removeEventListener uses equality against handlers that have previously been added to decide which handler should be removed.

    So first you are adding one handler, then trying to remove one that was never added in the first place. Net result is that the added handler is not removed.

    If instead, you store the added handler in a variable, then remove the same one, all will be good:

    const handler = (evt) => onHeaderKeyDown(parentElement, columnApi, evt)
    headerElement.addEventListener('keydown', handler);
    headerElement.removeEventListener('keydown', handler);