removeEventListener of Anonymous function javaScript

Viewed 5746

how can i remove this event listener I have tried but below code and it does not seam to bare any fruit

class Tag {
  constructor(name){
      this.tag = document.createElement(name);
  }
      removeEvent(e,func){
      this.tag.removeEventListener(e,func,false);
  }
      addEvent(e,func) {
      this.tag.addEventListener(e,func,false);
  }

}

let tag = new Tag();
tag.addEvent('click',(e)=> {
   console.log('something');
});

How do I get the removeEvent to work? please help I specifically need how to reference the anonymous function since this works.

 function handler(e){
     // code for event
 }

 tag.addEventListener('click',handler,false);  
 tag.removeEventlistener('click',handler,false);

I have tried adding

  removeEvent(e,func) {
      func.ref = function (){
          return arguments.callee;
      }

      this.tag.removeEventListener(e,func.ref,false);

  }

Just doesn't work given now we would be referring to func.ref as the function reference;

4 Answers

Simple way to remove anonymous event listener

A nice and simple way I found to remove eventListener that uses anonymous functions is to add these two functions into your code:

let events = new Map();
function addListener(element, event, callback, id) {
    events.set(id, callback);
    element.addEventListener(event, callback);
}

function removeListener(element, event, id) {
    element.removeEventListener(event, events.get(id));
    events.delete(id);
}

Anonymous function are great to keep the this context, and didn't found a good way to have both this, and the ability to remove the eventListener.

Example

let events = new Map();

function addListener(element, event, id, callback) {
  events.set(id, callback);
  element.addEventListener(event, callback);
}

function removeListener(element, event, id) {
  element.removeEventListener(event, events.get(id));
  events.delete(id);
}


let btn = document.getElementById('btn');
let cpt = 1;
addListener(btn, 'click', 'btnClick', e => {
  btn.innerHTML = `x${++cpt}`;

  if (cpt === 3) {
    removeListener(btn, 'click', 'btnClick');
  }
});
<button id="btn">x1</button>

Related