Sobes.tech
Junior

What is delegation?

sobes.tech AI

Answer from AI

Event delegation is a design pattern that allows a single event handler to manage events for multiple child elements. Instead of attaching a handler to each element, the handler is attached to the parent element. When an event occurs on a child element, it "bubbles" up to the parent, where the handler can intercept and handle it.

How it works:

  • The event is generated on the target element (e.g., <button>).
  • The event propagates up the DOM tree to the parent elements.
  • The event handler attached to the parent element intercepts the event.
  • In the handler, you can determine which specific child element triggered the event using event.target.

Advantages:

  • Performance: Fewer event handlers, reducing memory and CPU usage, especially for large lists or tables.
  • Ease of management: Easier to add and remove elements from the DOM, as there's no need to constantly attach/detach handlers.
  • Code cleanliness: Less repetitive code for attaching handlers.

Example:

Suppose we have a list of items, and we want to respond to clicks on each item.

Without delegation, we would attach a handler to each <li>:

// Get all <li> elements
const listItems = document.querySelectorAll('li');

// Attach handler to each element
listItems.forEach(item => {
    item.addEventListener('click', function() {
        console.log('Clicked on:', this.textContent);
    });
});

With delegation, we attach a handler only to the <ul>:

// Get the parent list
const list = document.querySelector('ul');

// Attach handler to the list
list.addEventListener('click', function(event) {
    // Check if the click was on an <li> element
    if (event.target.tagName === 'LI') {
        console.log('Clicked on:', event.target.textContent);
    }
});

In this example, we use event.target to determine which <li> was clicked.