javascript – remove event listener with parameters-ThrowExceptions

Exception or error:

I am trying to remove some listeners attached to certain array of elements.

As I am adding the event listeners I cannot get a reference to the parameters I needs. I have been doing some research and found out that can be solved using closures, but I can’t figure out very well how to do it

here is my function reference

const editTask = function (element, taskIndex) {
   const handler = function(event) {
   // my code ...
   }
}

and this is how I am adding the listeners

function addEditListeners() {
  const editButtons = [].slice.call(document.getElementsByClassName("edit-btn"));
  console.log('editbuttons', editButtons);
  //editButtons.forEach(function (element) {
  //    element.removeEventListeners("click", editTask);
  //});
  editButtons.forEach(function (element, index) {
    element.addEventListener("click", handler);
  });
}

I have tried sending the parameters in parenthesis but the editTask is undefined, what am I doing wrong?

How to solve:

Notice that you are passing handler which only exists in the editTask function and nowhere else, your listener adding function should be like this

editButtons.forEach(function (element, index) {
    element.addEventListener("click", (e) => editTask(element, index, e));
  });

Also I see you want an event in there as well so you should pass it in edit task

const editTask = function (element, taskIndex, event) {
   const handler = function(event) {
   // my code ...
   }
   handler(event);
}

Leave a Reply

Your email address will not be published. Required fields are marked *