简体   繁体   中英

remove event listener with parameters

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM