Event delegation utilizes event bubbling to manage one type of event with just one event handler.

For example, the Click event bubbles to document. This means that you can specify an onclick event for the entire page to handle the event handler instead of specifying an event handler for each clickable element.

<ul id="myLinks">
    <li id="goSomewhere">Go Somewhere</li>
    <li id="doSomething">Do Something</li>
    <li id="sayHi">Say Hi</li>
</ul>
Copy the code

Common practice:

let item1 = document.getElementById("goSomewhere")
let item2 = document.getElementById("doSomething")
let item3 = document.getElementById("sayHi")

item1.addEventListener("click",(event) => {
    location.href = "xxx";
});

item2.addEventListener("click",(event) => {
    document.title = "I changed the document's title";
});

item3.addEventListener("click",(event) => {
    console.log("hi");
});
Copy the code

Using event delegates, you can solve the problem by simply adding an event handler to the common ancestor node of all elements

let list = document.getElementById("myLinks"); list.addEventListener("click",(event) => { let terget = event.target; switch(targetr.id){ case "doSomething": document.title = "I changed the document's title"; break; case "goSomewhere": locetion.href = "xxx"; break; case "sayHi": console.log("hi"); break; }});Copy the code

Here we just add an onclick event handler to the

Because all list items are descendants of this element, their events bubble up and are eventually handled by this function. However, the event target is each list item that is clicked, which can be determined by checking the ID attribute of the Event object, and then performing the corresponding action.

Compared to the previous code that did not use event delegates, the code that uses event delegates does not cause an early delay because only one DOM element is accessed and an event handler is added.

Event delegation has the following advantages:

  1. The Document object is always available, and you can add event handlers to it at any time (without waiting for a DOMContentLoaded or Load event).
  2. Save time spent setting up page event handlers. Specifying only one event handler saves both DOM references and time.
  3. Reduce the memory required for the entire page and improve overall performance.