event (event delegation)

1. Basic concepts

Event delegation (Event Delegation), also known as event delegation. is a common technique for binding events commonly used in JavaScript. As the name implies, "event proxy" is to delegate the response events (click, keydown...) that originally need to be bound to the child elements to the parent element, and let the parent element take on the role of event monitoring . The principle of event proxy is the event bubbling of DOM elements.

 The child's event is handed over to the parent to respond, and the correct child is found through e.target

<script>
document.body.onclick = function() {
     e.atrget   //真正发生事件的标签
     alert(e.target.innerHTML)
}
</script>

Event bubbling
The principle of event delegation mentioned above is the event bubbling of DOM elements, so what is event bubbling?

When an event fires, it propagates between child and parent elements. This propagation is divided into three stages

As shown in the figure above, event propagation is divided into three stages:

Capture phase: from the window object to the target node (from the upper layer to the bottom layer) is called the "capture phase", and the capture phase will not respond to any events; the target phase:
triggered on the target node, called the "target phase"
Bubbling phase: The window object is passed back from the target node (from the bottom layer to the upper layer), which is called the "bubbling phase". Event proxy is to use the event bubbling mechanism to bind the events that the inner layer needs to respond to the outer layer;

Advantages of event delegation

[1] It can save a lot of memory usage and reduce event registration. For example, it is very good to proxy all click events of li on ul

<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  ......
  <li>item n</li>
</ul>
// ...... 代表中间还有未知数个 li

As shown in the above code, if a function is bound to each li list item, the memory consumption is very large, so a better solution is to bind the click event of the li element to its parent element ul On the body, when the event is executed, match and judge the target element.

[2] It can be realized that when a new sub-object is added, there is no need to bind it again (dynamic binding event)

Assuming that there are only a few list items li in the above example, we bind events to each list item;

In many cases, we need to dynamically add or delete list item li elements through AJAX or user operations, so we need to re-bind events for newly added elements and unbind events for elements to be deleted every time there is a change;

If you use event delegation, there is no such trouble, because the event is bound to the parent layer, and it has nothing to do with the increase or decrease of the target element. The execution to the target element is matched in the process of actually responding to the execution event function ; So using events can reduce a lot of repetitive work in the case of dynamic binding events.

Basic implementation

[1] JavaScript natively implements event delegation

For example, we have an HTML fragment like this

<ul id="myLinks">
  <li id="goSomewhere">Go somewhere</li>
  <li id="doSomething">Do something</li>
  <li id="sayHi">Say hi</li>
</ul>

Traditionally, you need to add 3 event handlers for them like this

    var item1 = document.getElementById("goSomewhere");
    var item2 = document.getElementById("doSomething");
    var item3 = document.getElementById("sayHi");
 
    item1.onclick = function() {
      location.href = "http://www.baidu.com";
    };
    item2.onclick = function() {
      document.title = "事件委托";
    };
    item3.onclick = function() {
      alert("hi");
    };

If you did this for all clickable elements in a complex web application, you'd end up with untold amounts of code for adding event handlers. At this point, you can use event delegation technology to solve this problem. With event delegation, simply add an event handler at the highest possible level in the DOM tree, as shown in the following example

    var item1 = document.getElementById("goSomewhere");
    var item2 = document.getElementById("doSomething");
    var item3 = document.getElementById("sayHi");
 
    document.addEventListener("click", function (event) {
      var target = event.target;
      switch (target.id) {
        case "doSomething":
          document.title = "事件委托";
          break;
        case "goSomewhere":
          location.href = "http://www.baidu.com";
          break;
        case "sayHi": alert("hi");
          break;
      }
    })

Guess you like

Origin blog.csdn.net/Cc200171/article/details/124981986