V
V
Vladimir2018-02-19 19:26:07
JavaScript
Vladimir, 2018-02-19 19:26:07

How to pass an arrow function with parameters to an eventlistener?

There is an arrow function, for example: How to pass it to the event listener with parameters? When I pass it, it immediately calls itself without a click, probably because of the call operator (), but how then to pass the parameters if I need to call it every time with different parameters in different handlers? Don't want to duplicate code.
let myFoo = (param1, param2) => {...}

myBtn.addEventListener ( 'click', myFoo( btn1, btn2) );

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-02-19
@connecticum

Not enough conditions, but I assume that instead of myFoo(...) you need to pass an anonymous function in which myFoo(...) will be called with the parameters you need.
PS: the second argument should be a function, not its result, well, the arguments are still, whatever one may say, are set when the function is called and not when it is passed.
something like this:

myBtn.addEventListener ( 'click', function() {
    myFoo( btn1, btn2)
});

Either return a function from myFoo and use its arguments, which will be in the closure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question