“This is the 26th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

In this section, we’re going to focus on event delegation, also known as event proxy, which is an application for bubbling up events. What is event delegation?

First, we need to know that in JavaScript, the number of event handlers added to a page is directly related to the overall performance of the page. There are several factors contributing to this problem.

  • First, 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.

preface

👉 events bubble up in JavaScript

👉 JavaScript event capture do you know?

Case Study 1

Let’s start with an example:

The following list contains three list items that perform an action when clicked. Traditionally, you add three event handlers to them as follows. If you did this for all clickable elements in a complex Web application, the result would be untold code for adding event handlers.

So to solve this problem, we have a solution called event delegation. Event delegates take advantage of event bubbling and manage all events of a certain type by specifying a single event handler.

In simple terms, when an element’s event fires, it delegates the task to the parent element

Now we modify the above code using the event delegate as follows

<ul id="myLinks"> <li id="goSomewhere">Go somewhere</li> <li id="doSomething">Do something</li> <li id="sayHi">Say hi</li> </ul> var list = document.getElementById("myLinks"); EventUtil.addHandler(list, "click", function(event){ event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); switch(target.id){ case "doSomething": document.title = "I changed the document's title"; break; case "goSomewhere": location.href = "http://www.wrox.com"; break; case "sayHi": alert("hi"); break; }});Copy the code

Code analysis:

In this code, we add an onclick event handler for just the

    element using the event delegate. Since all list items are children of this element, and their events bubble up, click events are ultimately handled by this function.

We then use the ID to determine what the corresponding list item needs to do, and by adding only one event handler, we achieve the same effect as before, with less code consumption and memory footprint.

Case Study 2

There are other uses for event delegates, such as if you have a bunch of menu buttons, and traditionally, depending on your needs, you need to add an onclick to each button

But with event delegate you can do this by first adding data-action attributes for buttons that have method calls

<div id="menu"> <button data-action="edit"> </button> <button data-action="load"> Load </button> <button Data-action ="search"> </button> </div>Copy the code

You then add a handler for the entire menu, which reads the attribute and executes the method.

class Menu { constructor(elem) { this._elem = elem; // Bind this.onclick to this, otherwise the internal this will refer to the DOM element (elem) instead of the Menu object elem. OnClick = this.onclick.bind (this); } edit() {console.log(' edit ')} Load () {console.log(' load ')} search() {console.log(' search ')} onClick(event) {let action = event.target.dataset.action; if (action) { this[action](); }}; } new Menu(menu);Copy the code

When to use event delegate?

Applicable circumstances:

  • All events that use buttons (most mouse and keyboard events) are suitable for event delegation techniques such asClick, mouseDown, mouseup, keyDown, keyUp, keyPress.And so on.

Not applicable:

  • The focus, the blurOr something like that, it doesn’t have bubbling, so you can’t use event delegate.
  • Mouseover and mouseoutThere are events bubbling, but handling them requires special care because they are often computed and can be difficult to handle.

References:

Javascript Advanced Programming

Event delegation


🎨 [thumbs up] [concerns] don’t get lost, more front-end dry goods waiting for you to unlock

Phase to recommend

👉 Take a look at JS prototype inheritance

Do you know how to use getters and setters in 👉 JS?

👉 In-depth understanding of ES6 arrow objects

👉 JS decorator pattern instance analysis