What is event delegation?

Event delegation uses event bubbling. You can manage all events of a certain type by specifying a single event handler.

Why use event delegate?

In JavaScript, the number of event handlers added to a page is directly related to the overall performance of the page. Every function is an object and takes up memory; The more objects in memory, the worse the performance. Second, the number of DOM accesses caused by having to specify all event handlers beforehand delays the interaction ready time for the entire page.

The principle of event delegation

The event bubbling

Event delegate implementation example

    <ul id='ul'>
        <li id='home'>Home page</li>
        <li id='about'>About us</li>
        <li id='login'>The login</li>
    </ul>
Copy the code
    let ulDom = document.getElementById('ul')

    // Add an event listener
    function addHandler(element, type, handler) {
        // Cross-browser adaptation
        if (element.addEventListener) {
            element.addEventListener(type, handler, false)}else if (element.attachEvent) {
            element.attachEvent('on' + type, handler)
        }else {
            element['on' + type] = handler
        }
    }

    function proxy(e) {
       e = e ? e : window.event;

       // Returns the target node of the event
       let target  = e.target || e.srcElement;
        
       // Trigger different actions according to different clicks
       switch(target.id) {
           case 'home':
                location.href = 'http://localhost:8000/home'
                break;
           case 'about':
               location.href = 'http://localhost:8000/about'
                break;
           case 'login':
               location.href = 'http://localhost:8000/login'
                break;
       }
    }

    addHandler(ulDom, 'click', proxy)


    /** * Adds an onClick event handler for ul tags only using the event delegate. * Since all list items are children of this element and their events bubble up, click events are eventually handled by this function. * Because the event target is the list item that is clicked, the id attribute can be detected to determine the appropriate action. * Because only one DOM element is retrieved, only one event handler is added. This method takes up less memory. The result is the same for the user * all button events used (mouse and keyboard events) can use event delegation techniques * */
Copy the code

Next article – How to encapsulate a generic event handler