I have a bunch of divs(current_items). Each div has a button – "remove div" (remove_buttons).
Each button has a click listener. After clicking on any button I need all listeners for all buttons to be removed. But removeEventListener
doesn’t work. Do you know why? Please let me know.
My JS code is:
var current_items = document.getElementsByClassName('cart_post_wrap'),
remove_buttons = document.getElementsByClassName('cart_remove_button');
// This is a function for click listeners.
function removeItem(object1, obeject2, object3, index)
{
return function ()
{
//Some code which removes divs from DOM.
//And then removes all listeners:
for (let i = 0; i < current_items.length; i++)
{
remove_buttons[i].removeEventListener("click", removeItem);
}
}
}
// Here I create my click listeners for each button.
for (let i = 0; i < current_items.length; i++)
{
remove_buttons[i].addEventListener("click", removeItem(current_items[i], ids_list[i], types_list[i], i));
}
2
Answers
In order for
removeEventListener
to work, you need to pass the reference to the function you added as the event listener. You are not saving the return value of theremoveItem
function call when you’re adding the event listeners – you’re just passing the event listener there, and on removing, you’re passing a reference to theremoveItem
factory function, which was never added as an event listener, hence why this is not working.When creating the event listeners, you need to store them somewhere, and pass them to
removeEventListener
. Something like this should work:It’s because
remove_buttons[i].addEventListener("click", removeItem(current_items[i], ids_list[i], types_list[i], i));
is not adding theremoveItem
function as the event listener; it’s calling theremoveItem
function and adding whatever it returns as the event listener; in this case, an in-lined function withreturn function () { ... }
.Later, you try to remove the
removeItem
function as the event listener, but as explained above, it was not added as the event listener in the first place.If you’re planning on removing the elements from the DOM anyway, as your comment in the code suggests, there’s no point in removing the buttons’ click event listeners: if they are gone from the DOM, they can no longer be clicked. Forget about removing the click event listeners, and instead have much cleaner code as a result.