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???