当前位置:网站首页>Principle of event delegation
Principle of event delegation
2022-06-28 04:15:00 【weixin_ forty-seven million one hundred and sixty-four thousand】
The Commission of the event ( agent Delegated Events) Principle and advantages and disadvantages of
A: entrust ( agent ) Events are those that are bound to the parent element , But it will be moved only when certain matching conditions are met . This is achieved by the bubbling mechanism of events ,
Advantage is ( effect ):
(1) Can save a lot of memory , Reduce event registration , For example table On behalf of all td Of click It's a great event
(2) It can be realized that when a new sub object is added, there is no need to bind the event to it again , Especially for dynamic content
The disadvantage is that :
The application of event proxy should be limited to the above requirements , If all events are represented, there may be event misjudgment , That is, the event that should not trigger the event is bound to the event .
target It's the object that triggers the event ,target For the element you clicked
var ul=document.querySelector("ul");
ul.onclick=function(e){
//e Here it means event object
var target=e.target||e.srcElement;//target Get the target that triggers the event (li)
if(target.nodeName.toLowerCase()==' li '){
// The goal is (li) Node name to lowercase , If you don't convert it, it's capital letters
alert(target.innerHTML)
}
}
First of all , Let's first talk about the origin of event delegation : Because the event handler can be web Applications provide interactive capabilities , Therefore, many developers will indiscriminately add a large number of handlers to the page . stay js in , The number of event handlers added to the page is directly related to the overall O & M performance of the page . There are many reasons for this problem . First :
1 Functions are objects , Will take up memory , The more objects in memory , The worse performance
2 Specifying all event handlers in advance results in dom Number of visits , Ready events that delay the interaction of the entire page .
therefore : The solution to the problem of too many event handlers is event delegation .
Take a chestnut
Insert picture description here
<ul id = 'ul1'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
...
<li>100</li>
</ul>
If we have 100 individual li label , If you want to achieve click li Turn red , Although we can use for loop , For each li Add event , So that adds 100 An event handler , If in a complex web In the program , In this way , The result is an innumerable number of added event handlers . So here is a waste of resources . So here's a conclusion :
Event delegation , The most important function is to improve the efficiency of the program .
Now that the event Commission has come out , Let's talk about the principle of event entrustment . Let's start with a concept : Flow of events .
The flow of events is divided into 1. Event capture : When an event is triggered , from Window Object triggering , Continuously passing through the lower nodes , Until the target node . The process before the event reaches the target node is the capture phase . All the nodes that pass through , Will trigger the corresponding event
2. Event Bubbling : When the event reaches the target node , It will return along the route of the capture phase . Again , All the nodes that pass through , Will trigger the corresponding event. Now go directly to the code , Let's learn about event capture and event bubbling
Insert picture description here
<div id = 'div1'>
grandpa
<div id = 'div2'>
father
<div id = 'div3'>
Grandson
</div>
</div>
</div>
<style>
div{
padding: 50px; color: white; font-size: 20px;}
#div1{
background-color: orange;}
#div2{
background-color: blue;}
#div3{
background-color: red;}
<style>
for example , We all give these three div It's also bound with click events , When I click on my grandson , As a general rule , Did you also click on father and grandpa , So , We clicked on grandson's click event , Then this event will be to dom Tree propagation , That's the order
div3>div2>div1>body>html>document…
1
So , This is the bubble , Event capture is just the opposite , In the event capture process ,document First received click event , And then along document Down , All the way to the actual target of the event . That is, in this order
document>html>body>div1>div2>div3
1
But the traditional event binding has no way to achieve event capture , Our default event flow is still event bubbling ! Event Bubbling : Trigger step by step from the inside out ( Components that must be parent-child )( Default event flow ) Event capture : Trigger from the outside to the inside and step by step to the outside ( Components that must be parent-child ) Traditional event binding cannot be implemented good , Someone here asked , Since we are talking about event entrustment , Why do you want to bubble and capture the events of the event flow here . In fact, the event delegation principle we want to implement is event bubbling ! Then let's move on to the above case , Now the demand is coming , If you want to give 100 individual ,1000 individual li Tags are bound at the same time onclick event , Let's use the most efficient way to bind , you 're right , Event delegation .
<ul id = 'ul1'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>100</li>
</ul>
Here 100 individual li Tag binding events , When we click li when , The currently clicked li The label background displays red . At the same time , Here comes another problem : The parent has so many child elements , How to distinguish which child element an event should be ? The answer is that one of our events event object , and event There are... Recorded in the object “ Event source ”, It is the child element of the event . When we were writing , This acquisition event The event source of is IE Compatible . The acquisition in the lower version is window.event.srcElement; In our other browsers, you can directly use event.target Acquired , Our general way of writing is
var target = event.target || window.event.srcElement;// Short circuit operation
1
Let's implement it through event entrustment
var oUl = document.getElementById("ul1");
// entrust ul Click event on , The currently clicked li The node turns red .
oUl.onclick = function(ev){
// Get event object short circuit operation , compatible IE
var e = ev || window.event;
// Get the event source target It should also be compatible here IE
var target = e.target || window.event.srcElement;
// Judge target Whether the element nodes meet the requirements
if(target.tagName.toLowerCase() == "li"){
// Will currently click this li The node turns red
target.style.backgroundColor = 'red';
}
}
``` Here we really implement an event delegation , and , Only one event is bound , Give this event to ul label . Let's click li, Then through the bubble principle Events on child elements will bubble up on parent elements Is it more convenient than the traditional implementation method , And save a lot of memory resources . There are not so many event handlers , That's right web A performance optimization of the program . Sum up , You can conclude that you want to implement event delegation , Three conditions that must be complied with : 1、 Find the parent node or ancestor node of the node to add the behavior to 2、 Bind the event to the found parent node 3、 Find the trigger object , Judge whether it meets the requirements , If the requirements are met , Follow up . In fact, the benefits of event delegation do not stop here , Another need , Give a button on the page , By clicking the button , And then to ul Add a new... To the label ul label . Then this new one li label , You should also realize the same functions as the brother level above . In traditional events , We need to add new binding events , Isn't that very troublesome . ```js
// In order to identify the newly labeled content
var i = 6;
var oBtn = document.getElementById("btn1");
oBtn.onclick = function(){
// Create a new li label
var newLi = document.createElement("li");
// Add content to the new tag
newLi.innerHTML = 111 * i++;
// Will add new li label , Add to ul End of element
oUl.appendChild(newLi)
}
We use event delegation to implement , The above new li label , Also enjoy li Same function as brother level . That is to add nodes after , Have the previously bound functions . The advantages of event delegation : 1. Improve performance : Each function takes up memory space , Just add an event handler to proxy all events , Less memory . 2. Dynamic monitoring : Using event delegates, you can automatically bind dynamically added elements , That is to say, the new node does not need to be added actively, it can also have the same events as other elements . So today's js That's all for the event entrustment , Welcome to spray , The comment area is reserved for you
边栏推荐
- Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"
- C语言十进制与BCD码的相互转换
- first. Net core MVC project
- Understanding and learning of parental delegation mechanism
- 11_刻意练习精讲
- From zero to one, I will teach you to build a "search by text and map" search service (I)
- Multi project design and development · introduction to class library project
- Little knowledge about function templates --
- 公司领导说,个人代码超10个Bug就开除,是什么体验?
- 等保三级密码复杂度是多少?多久更换一次?
猜你喜欢

Notes to friendship chain

RT thread bidirectional linked list (learning notes)

Digital promising, easy to reach, Huawei accelerates the layout of the commercial market with "five pole" star products

Pinda general permission system (day 5~day 6)

关于 SY8120I 的DC-DC的降压芯片的学习(12V降至3.3V)

软件测试报告怎么编写?第三方性能报告范文模板来了

Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"

抖音實戰~關注博主

How to write a software test report? Here comes the third party performance report template

leetcode - 329. Longest increasing path in matrix
随机推荐
光伏板怎么申请ASTM E108阻燃测试?
软件测试报告怎么编写?第三方性能报告范文模板来了
ELK 搭建日志分析系统 + Zipkin服务链路追踪整合
TFTLCD display experiment of mini plate based on punctual atom stm32
11_刻意练习精讲
Visualization of loss using tensorboard
从零到一,教你搭建「以文搜图」搜索服务(一)
视频爆炸时代,谁在支撑视频生态网高速运行?
RT thread bidirectional linked list (learning notes)
MSc 307 (88) (2010 FTPC code) Part 5 low flame spread test
How to write a software test report? Here comes the third party performance report template
[small program practice series] e-commerce platform source code and function implementation
基于正点原子stm32的mini板的TFTLCD显示实验
With the transformation of automatic empowerment, Feihe dairy accelerates its move towards digitalization!
Design a stack with getmin function
Problems with cat and dog queues
AS 3744.1标准中提及ISO8191测试,两者测试一样吗?
Uncertainty principle
Multi project design and development · introduction to class library project
Component splitting practice