0

I have the following event listener that I set in my JS after a successful AJAX request:

var pageButtonsParentElement = document.getElementById("page-buttons");
pageButtonsParentElement.addEventListener('click',
    event => {
        let selectedPageButton = event.target;
        if (selectedPageButton.classList.contains("page-item")){
            updatePageButtonFormatting(selectedPageButton);
            let selectedPageNumber = selectedPageButton.getAttribute("data-page-number");
            inputObject = createInputObject(selectedPageNumber);
            // new CallClass(inputObject); 
        }
})

According to the Mozilla docs, I can call the removeEventListener() method and pass in the element as well as the function to be removed (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener). I'm not sure how to do this when my function is "event => ..."

  • You can't unless you store a reference to it somewhere. – pilchard Feb 23 '22 at 22:23
  • declare the function as usual: `function pageButtonsClick(event) { ... }` then use `pageButtonsParentElement.addEventListener('click', pageButtonsClick)` (also note that using arrow functions as event listeners might bite you later when you want to use `this` inside the listener to refer to the clicked button) –  Feb 23 '22 at 22:24
  • 1
    Does this answer your question? [removeEventListener of Anonymous function javaScript](https://stackoverflow.com/questions/44229560/removeeventlistener-of-anonymous-function-javascript) – pilchard Feb 23 '22 at 22:24
  • 1
    also: [removeEventListener on anonymous functions in JavaScript](https://stackoverflow.com/questions/4950115/removeeventlistener-on-anonymous-functions-in-javascript) and [Removing an anonymous event listener](https://stackoverflow.com/questions/3106605/removing-an-anonymous-event-listener) – pilchard Feb 23 '22 at 22:25
  • Also, you can always set an external state variable like "stuffHappened = true;" then branch inside the event handler (instead of removing it) –  Feb 23 '22 at 22:27

1 Answers1

0

You need a reference to the function you want to remove.

If you don't keep a reference to it, you can't remove it.

Keep a reference to it.

const listener = event => { ... };
foo.addEventListener("click", listener);
foo.removeEventListener("click", listener);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335