Event delegate (proxy, delegate)
The characteristics of event bubbling itself, will bring harm, will also bring benefits, we need to flexibly grasp. In life, there are the following scenarios: there are 100 students in our class, and the Courier has 100 couriers. It takes a long time to send them one by one. At the same time, each student needs to queue up to get it, which takes a long time. Why? Solution: The Courier entrusted 100 packages to the homeroom teacher. The homeroom teacher put the packages in the office and the students could get them by themselves after class. Advantage: Courier save trouble, entrusted to the class teacher can go. The students also get convenient, because I believe in the teacher.
The characteristics of event bubbling itself, will bring harm, will also bring benefits, we need to flexibly grasp. The application also has a scenario like this:
<ul>
<li>You know what? There should be a cartridge</li>
<li>You know what? There should be a cartridge</li>
<li>You know what? There should be a cartridge</li>
<li>You know what? There should be a cartridge</li>
<li>You know what? There should be a cartridge</li>
</ul>
Copy the code
Clicking on each LI will bring up a dialog box. Previously, you had to register events for each Li, which was very laborious, and the more times you accessed the DOM, the longer the interaction ready time for the entire page.
Event delegation:
Event delegates are also called event proxies, or event delegates in jQuery.
How event delegation works:
Instead of setting event listeners individually for each child node, event listeners are set on its parent node and then influence each child node to be set using the bubbling principle.
For example: register a click event for UL, then use the target of the event object to find the current hit li, because the event will bubble up to UL, ul has a registration event, which will trigger the event listener.
Function of event delegate:
We only manipulated the DOM once, improving the performance of the program.
<ul>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
</ul>
<script>
// The core principle of event delegation is to add listeners to the parent node and use event bubbling to affect each child node
var ul = document.querySelector('ul');
ul.addEventListener('click'.function(e) {
alert('You know what? I should have a frame in hand! ');
// e.target this will get the object we clicked on
e.target.style.backgroundColor = 'pink';
})
</script>
Copy the code