Using addEventLIstener and removeEventListener, is there a way in JavaScript to pass a value to the handler function, via an anonymous function, and still remove the event later in the code?
For example, I was using element.addEventLister( 'mousedown', func, false )
and then later removing the same; but if want element.addEventListener( 'mousedown', function() { func(x); }, false )
, the event listener can't be removed for an anonymous function, or at least that is what I read on MDN and I haven't been able remove it.
I wanted to make a closure on func such that the event would pass the value of x at the time the event listener was added/registered rather than the value when the event is triggered. That worked, but the listener couldn't be removed later.
Thank you.
After using bind successfully for some cases, I don't understand how to get the event object when using bind and still be able to remove the event listener afterward.
For example, the following code makes a new function f that is like func with a closure on x set to value 2. The only purpose in doing this is to make the listener removable and still pass arguments to the handler function. But how can the focus event object be available to f or func and the listener still be removed?
let x, f;
function func(a) { /* code...*/ }
x = 2;
f = func.bind(null, x);
element.addEventListener( 'focus', f, false );
x = 5;
// and later element.removeEventListener( 'focus', f, false );
In the case where the event listener won't be removed, I have been using something like element.addEventListener( 'focus', function(evt) { func(evt, a); }, false)
and declaring func as func(evt, a); but that listener can't be removed directly because the handler is an anonymous function.
I'm assuming there must be a simple way to do this but I'm not understanding it at this point.
Thank you.