1. Event delegation

1. What is event delegation

In JavaScript, an event delegate, also known as event hosting or event proxy, binds the events of the target node to the ancestor node. This simple and elegant way of registering events is based on the fact that during event propagation, layer by layer bubbles can always be caught by the ancestor node.

The benefits: optimized code, improved performance, true separation of HTML and JavaScript, and prevention of loss of events registered during dynamic node addition or removal.

2. Why event delegate

1) Save the number of listeners, that is, save memory

Imagine a scenario where we want to develop a web version of a minesweeper. On a web page, there is a

with the id lei.

has 20*20=400 < buttons > nested within it.

<div id="lei">
    <button>mouth</button>
    <button>mouth</button>
    <!-- 一共400个button -->
    <button>mouth</button>
</div>
Copy the code

So how do you add click events to those 400

Option 1: Traverse all

Option 2: Add an event delegate to

as follows:
lei.addEventListener('click'.(e) = > {
    const t = e.target;
    if (t.tagName.toLowerCase() === 'button') {
        console.log('Button clicked'); }});Copy the code

In the code above, the listener for the event is defined on the

node, but it actually handles the click event on the child node

2) Dynamic elements can be listened on

What if the

// Add button to div dynamically with js
function generateButtons() {
    for (let i = 0; i < 400; i++) {
        const btn = document.createElement('button'); lei.appendChild(btn); }}Copy the code

In this case, the

node can only be listened to through an event delegate to add the ability to handle the click event to

Block the default action

How do you prevent the browser from triggering the default action for certain events, such as clicking on the tag to redirect to the href page?

In browsers that support addEventListener(), it’s possible to cancel the event’s default action by calling the event object preventDefault() method. In IE prior to Internet Explorer 9, you could achieve the same effect by setting the returnValue property of the event object to false. The following code combines three techniques to cancel events:

function cancelHandler(event) {
    var event = event || window.event;/ / compatible with IE
    // Cancel the default behavior related to events
    if(event.preventDefault) { // Standard technology
        event.preventDefault();
    }
    if(event.returnValue) { // Compatible with IE prior to IE9
        event.returnValue = false;
    }
    return false; // Used to handle handlers registered with object properties
}
Copy the code

Three, prevent the event bubbling

1. What is event bubbling?

Here’s an example:

<div id="p" style="width: 200px; height: 200px; background-color: red;">
    <div id="c" style="width: 100px; height: 100px; background-color: blue;"></div>
</div>
Copy the code

Add onClick events for each of the two divs nested above

p.onclick = () = > console.log('p is clicked');
c.onclick = () = > console.log('c is clicked');
Copy the code

1) When the mouse clicks on the outer red

, the console outputs

p is clicked

2) When the mouse clicks on the inner blue

, the console outputs

c is clicked

p is clicked

2. The concept of event bubbling

The browser traverses the window from the bottom to the top of the button clicked by the user, triggering event handlers one by one.

W3C event model/event mechanism: Capture and bubble for each event.

3. How to prevent events from bubbling

1) event. StopPropagation ()

Let’s rewrite the C. onclick part of the js code

c.onclick = (event) = > {  
  console.log('c is clicked');
  event.stopPropagation();
};
Copy the code

Add event to the c onclick code and event.stopPropagation() to the last line;

This way, you can prevent events from bubbling: the console does not output P is clicked after c is clicked.

Note that event.stopPropagation() does not block the default action.

2) return false

c.onclick = () = > {  
  console.log('c is clicked');
  return false;
};
Copy the code

Prevent both event bubbling and default behavior by returning false.