educative.io

removeEventListener is not working

Hi there,

This is done using closure, but when I click on deactivate counting, removeEventListener don’t work.

        const countClicks = () => {
            let counter = 0
            
            return count = () => {
                counter += 1
                console.log(counter);
                countElement.textContent = counter;
            }
        }

        // start counting
        btnElement.addEventListener("click", countClicks()); // <-- here the function is invoke because of the inner function, after its execution the inner function is assigned to the click event handler. 

        // stop counting
        stopCountElement.addEventListener("click", () => {
            btnElement.removeEventListener("click", countClicks); // <-- here the function is invoke because of the inner function, after its execution the inner function is assigned to the click event handler.
        })

Hi Camarian!

I think firstly your solution needs to match ids with their respective elements in the HTML markup, so btnElement is actually myButton and stopCountElement is actually deactivate and countElement is countClicks.

That out of the way, let’s debug your stop countClicks function.

You are nearly right. It is just that the reference countClicks() being passed to removeEventListener() doesn’t match the original object reference. For that, we need to maintain the listener reference somewhere. Here’s one solution, although it introduces another global variable:

var listener;
const click = () => {
  let clickCountVar = 0;
  var count = () => {
    clickCountVar += 1;
    console.log(clickCountVar);
    clickCount.textContent = clickCountVar;
  };
  listener = count;
  return count;
};
document.getElementById("myButton").addEventListener("click", click());
document.getElementById("deactivate").addEventListener("click", () => {
  document.getElementById("myButton").removeEventListener("click", listener);
});

Kind Regards,
Mishaal
Developer Advocate

2 Likes

Thanks @Mishaal_Kazmi

1 Like