Course contentsShow
← JavaScript
Lesson 512 of 2,72313. ClosuresFree lesson

Event Handler Binding

Preserve context and parameters in event handlers by wrapping them in closures.

Event Handler Binding

You'll learn how to preserve context and parameters in event handlers by wrapping them in closures.

When you attach event handlers in JavaScript, you often need to pass additional data or preserve context that won't be available when the event fires. Closures solve this elegantly by "remembering" the variables from when the handler was created.

The Problem

Imagine you're creating buttons in a loop. You want each button to log its specific index when clicked:

for (var i = 0; i < 3; i++) {
  const button = document.createElement('button');
  button.textContent = `Button ${i}`;
  button.addEventListener('click', function() {
    console.log(i); // Always logs 3!
  });
}

This fails because all handlers share the same i, which ends up as 3 after the loop finishes.

The Closure Solution

Wrap the handler in a closure to capture each value:

for (let i = 0; i < 3; i++) {
  const button = document.createElement('button');
  button.textContent = `Button ${i}`;
  button.addEventListener('click', function() {
    console.log(i); // Logs 0, 1, or 2 correctly!
  });
}

Using let creates a new binding for each iteration, giving each handler its own i via closure.

Binding Custom Parameters

You can pass additional data into your handlers:

function createHandler(userId, action) {
  return function(event) {
    console.log(`User ${userId} performed ${action}`);
    console.log('Event:', event.type);
  };
}

button.addEventListener('click', createHandler(42, 'save'));

The closure captures userId and action, while the event object is passed when the handler executes.

Key Takeaway: Closures let event handlers "remember" variables from their creation context, solving the problem of passing data to handlers that execute later—each handler gets its own captured environment.