Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C2 · Lekcja 8
ZadanieHTML has <ul id='list'><li class='item' data-id='1'>One</li><li class='item' data-id='2'>Two</li><li class='item' data-id='3'>Three</li></ul>. Add ONE listener on #list that, when an .item is clicked, logs 'clicked: <id>' using event.target.closest('.item').dataset.id.

Delegowanie zdarzeń: jeden słuchacz na tysiąc pozycji

100 XP8 min
Teoria

The N-listener anti-pattern

document.querySelectorAll(".item").forEach((el) => {
  el.addEventListener("click", () => { /* ... */ });
});

Works fine for 5 items. With 5,000 items it's 5,000 listeners → memory bloat + slow first paint. Worse: dynamically-added items don't get the listener and silently break.

Delegation: one listener on the parent

list.addEventListener("click", (event) => {
  const item = event.target.closest(".item");
  if (!item) return;
  // handle the click on .item — works for items added later too
});

Events bubble. A click on a child <li> bubbles up to its parent <ul>. One listener on the parent catches every click on any .item, present or future.

Why event.target.closest

event.target is the exact element clicked — might be a deeper <span> inside the item. .closest(".item") walks up until it finds the nearest matching ancestor (or returns null). That's how you distinguish "user clicked something inside an item" vs "user clicked outside any item."

React et al. do this for you

Every modern framework uses delegation at the document root for performance. You don't think about it in React. Knowing the underlying pattern is what makes the framework feel obvious instead of magic.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.