2

I searched everywhere here for an answer to satisfy this question, but I couldn't find it. I did find this answer for action script and others that were similar, but none directly answered my question for Javascript.

I have an event listener which needs to pass in a parameter like so:

var parameter = "";
myVar.addEventListener('event', function(e){
    function_To_Call(e,parameter);
}, false);

How do I remove this event listener when I'm done?

YAHsaves
  • 1,697
  • 12
  • 33

3 Answers3

3

Here is another solution that will not need to keep a var outside of the function scope holding your custom value. By using closures. You will still have an outside function handle, but it looks cleaner to me and less error prone.

const handlerFabric = (someArg) => {
    return (e) => { 
        //Here you have access to your someArg, as well as the e coming in
        console.log(e); 
        console.log(someArg);
    }
}

const handler = handlerFabric('test'); //Set your custom arg here

myVar.addEventListener('event', handler);
myVar.EventListener('event', handler);
Symyon
  • 388
  • 2
  • 10
2

You need to have a standalone reference to the function you pass into addEventListener. For example:

var parameter = "";
const callback = function(e){
  function_To_Call(e,parameter);
}
myVar.addEventListener('event', callback);
// ...
myVar.removeEventListener('event', callback);

Whether parameter changes in the meantime is of no consequence, because the callback function is still static.

Note that to reduce unnecessary code, feel free to omit the third parameter to addEventListener, useCapture, which defaults to false already.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Don't use an anonymous function as the listener. Do something like:

var parameter = "";
var listenerFunction = function(event, parameter) {
    // code for function_To_Call goes here
}

myVar.addEventListener(event, listenerFunction);

And when you're done:

myVar.removeEventListener(event, listenerFunction);

See https://www.w3schools.com/jsref/met_element_removeeventlistener.asp

pseudobbs
  • 214
  • 1
  • 6