0

I'm trying to get a click handler function in javascript to allow multiple parameters and also still be able to access the event object from the browser.

Digging around on stack, I found this

https://stackoverflow.com/a/8941670/8140320

I tested it in a fiddle and it works. I don't understand why though.

https://jsfiddle.net/xzpzjLs1/10/

My JS code in the fiddle:

div=document.querySelector('div');
data = "data";

let testFunction = function (data) {
    return function (event){
    console.log(event);
   console.log(data);  
   };
 }

div.addEventListener('click', testFunction(data));

I read this article on closures and it helped but still don't understand.

https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8

What I think I know is:

When a click happens, testFunction is executed and data is passed.

testFunction returns a function (which creates a closure that stores local variables in scope)

the 'data' variable is in the closure because it was a parameter passed in

But what about 'event'...how does the return function know that 'event' is the event object from the browser???

Xia
  • 43
  • 2
  • 7
  • 2
    *"What I think I know is: When a click happens, testFunction is executed and data is passed."* Nope. :-) `div.addEventListener('click', testFunction(data));` **calls** `testFunction` (immediately), passing in `data`, and then passes its *return value* into `addEventListener` (exactly the way `foo(bar())` calls `bar` and passes its return value into `foo`). As you noted, its return value is a function. That function *closes over* the `data` parameter of the `testFunction`. So when the event occurs, it passes that value to `console.log`. – T.J. Crowder Apr 21 '18 at 17:34
  • 1
    THANK YOU!!! This helped me understand! – Xia Apr 21 '18 at 17:47

0 Answers0