How to remove event listener that does not directly call a function?

Issue

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 => …"

Solution

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);

Answered By – Quentin

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.