This is the 14th day of my participation in the August Text Challenge.More challenges in August

What is an event delegate?

In plain English, an element responds to an event (click, keydown……) Delegate to another element

Event delegates can only be used if events bubble up

This concept relies on the fact that if you want to run a piece of code by clicking on any of the large quantum elements, you can set event listeners on the parent node and have events that occur on the child node bubble up to the parent node, rather than setting event listeners individually for each child node.

Why use event delegates

A good example is a series of list items. If you want each list item to pop up a message when clicked, you can set the click event listener on the parent element

    so that the event will bubble from the list item to its parent element

      .

Suppose we have a UL parent element with multiple child elements:

<ul id="parent-list">
	<li id="post-1">Item 1</li>
	<li id="post-2">Item 2</li>
	<li id=">Item 3post-4">Item 4</li>
	<li id="post-5">Item 5</li>
	<li id="post-6"Item 6</li>
</ul>
Copy the code

For example, in the above example, there are only a few list items, and we bind events to each list item;

In many cases, we need to add or remove list items dynamically through AJAX or user operations, so every time we change, we need to re-bind events to the new elements, and unbind events to the elements to be deleted.

This is not the case with event delegates, because events are bound to the parent layer and are not related to the increase or decrease of the target element. Execution to the target element is matched in response to the actual execution of the event function.

So using events can reduce a lot of rework in the case of dynamically binding events.

How do I use this event delegate

document.getElementById("parent-list").addEventListener("click", function(e) {<font></font>
	
	if(e.target && e.target.nodeName == "LI") {<font>>
		console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");
	}
});
Copy the code

In this code, the target element is the element clicked below the #parent-list element, and some attributes of the target (such as nodeName, ID, etc.) can be more accurately matched to a type of #parent-list li element.

After you write code, you can think about whether the event delegate can help you with performance optimization. The most commonly used event is the click event. For other events, some may not be applicable, such as: Although events such as Mousemove and Mouseout have bubbling, they can only be calculated and located by location, which consumes high performance. For events like Focus and blur, there is no event bubbling mechanism, so you can’t use event delegates.