2

I am aware that you can use a closure and an anonymous function to pass arguments to an event handler, such as in:

function addClick(el, a, b) {
    el.addEventListener('click', function(e) {
        //a and b are available here
    });
}

But the problem is, when you do it this way, you can't remove the event listener since it's anonymous. Might need to both be able to pass arguments and remove the handler at some point, so I was wondering if this is possible in some way, or if there is another method to achieve the same end.

Only thing I can think of is to add properties to the handler and access them that way:

var handler = function() {
    console.log(handler.a);
    console.log(handler.b);
}

handler.a = 'argument1';
handler.b = 'argument2';

el.addEventListener('click', handler);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Joe
  • 1,117
  • 1
  • 8
  • 13
  • 1
    Regarding removing the handler, see [How to removeEventListener that is addEventListener with anonymous function?](http://stackoverflow.com/q/5660131/218196) – Felix Kling Nov 21 '14 at 07:52
  • That seems like a good option, I will look into it. Thanks! – Joe Nov 21 '14 at 16:00
  • 1
    "*I am aware that you can use a closure and an anonymous function*" - named functions are closures as well. No reason to put values as properties on the function object. – Bergi Jul 06 '22 at 19:54

0 Answers0