I would love to understand how exactly closure happens in this set of code and the way its implemented. I was watching a tutorial and the guy was giving example on callback function and he also gave example of closure there.
function attachEventListeners() {
let count = 0
document.getElementById("clickMe").addEventListener("click", function () {
console.log("Button Clicked", ++count)
})
attachEventListeners()
I thought in order for a closure-based count function to work, you had to return that function and assign it to a variable. Cause otherwise with each call of the outer function, count would initialize to 0. But how is it working here?
Closure is essentially a case of when a function inside of another function reaches outside of its own scope to grab variables that are in the scope of the outer function.
function attachEventListeners() {
let count = 0
document.getElementById("clickMe").addEventListener("click", function () {
console.log("Button Clicked", ++count)
})
In this example, the anonymous function handed to the event listener is grabbing and incrementing the variable count
in the attachEventListeners
function scope.
It is returning a new function to the listener every time, but each time you're attaching a new listener to the button which is silly.
Add one listener to the button. Call the handler which will return the closure as the function that will be called when the listener is fired.
const button = document.getElementById('clickMe');
// Call the handler that returns a function (your closure)
// that acts as the the listener. It only needs to be called once.
button.addEventListener('click', handler(), false);
function handler() {
let count = 0;
// The closure contains, and updates, the variable in
// its local environment when it's returned
return function () {
console.log('Button Clicked', ++count);
};
};
<button id="clickMe">Click me</button>