当前位置:网站首页>JS - event proxy and application scenarios
JS - event proxy and application scenarios
2022-07-23 21:48:00 【CaseyWei】

One 、 What is it?
Event agent , Generally speaking , It's about responding an element to an event (click、keydown......) Delegate to another element
As mentioned earlier , The flow of events will go through three stages : Capture phase -> Target stage -> bubbling phase , Event delegation is completed in the bubbling phase
Event delegation , Delegate the events of one or a group of elements to its parent or outer elements , What really binds events is the outer element , Not the target element
When the event responds to the target element , It will trigger the binding event of its outer element through the event bubble mechanism , And then execute the function on the outer element
Here's an example :
For example, a dormitory student also express to , A stupid way is for them to get it one by one
The better way is to entrust this matter to the dormitory head , Get one person out to pick up all the deliveries , Then distribute them to each student one by one according to the recipients
ad locum , Express delivery is an event , Each student refers to the one who needs to respond to the event DOM Elements , And the dormitory head who goes out to receive express delivery is the agent element
So it's the element that actually binds the event , According to the delivery process of the recipient, it is in the execution of the event , You need to determine which one or several of the proxied elements should match the current response event
Two 、 Application scenarios
If we have a list , There are a lot of list items in the list , We need to respond to an event when we click on a list item
<ul id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
......
<li>item n</li>
</ul>
If you bind a function to each list item one by one , That's very big for memory consumption
// Get target element
const lis = document.getElementsByTagName("li")
// Loop through binding events
for (let i = 0; i < lis.length; i++) {
lis[i].onclick = function(e){
console.log(e.target.innerHTML)
}
}
At this time, you can delegate Events , Bind the click event to the parent element ul above , Then match the target element when executing the event
// Bind events to the parent element
document.getElementById('list').addEventListener('click', function (e) {
// Compatibility processing
var event = e || window.event;
var target = event.target || event.srcElement;
// Judge whether it matches the target element
if (target.nodeName.toLocaleLowerCase === 'li') {
console.log('the content is: ', target.innerHTML);
}
});
Another scenario is that the above list items are not many , We bind events to each list item
But if the user can dynamically add or remove the list item elements at any time , Then you need to rebind events to the new elements every time you change them , Unbind the event for the element to be deleted
If you use an event delegate, you don't have this kind of trouble , Because events are bound to the parent layer , It has nothing to do with the increase or decrease of target elements , The execution to the target element is matched in response to the execution of the event function
for instance :
below html In structure , Click on input You can add elements dynamically
<input type="button" name="" id="btn" value=" add to " />
<ul id="ul1">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
Use event delegation
const oBtn = document.getElementById("btn");
const oUl = document.getElementById("ul1");
const num = 4;
// Event delegation , The added child element also has Events
oUl.onclick = function (ev) {
ev = ev || window.event;
const target = ev.target || ev.srcElement;
if (target.nodeName.toLowerCase() == 'li') {
console.log('the content is: ', target.innerHTML);
}
};
// Add a new node
oBtn.onclick = function () {
num++;
const oLi = document.createElement('li');
oLi.innerHTML = `item ${num}`;
oUl.appendChild(oLi);
};
You can see , Use event delegation , In the case of dynamically binding events, you can reduce a lot of repetitive work
3、 ... and 、 summary
Events suitable for event delegation are :click,mousedown,mouseup,keydown,keyup,keypress
From the above application scenario , We can see that there are two advantages of using event delegation :
Reduce the memory required for the entire page , Improve overall performance
Dynamic binding , Reduce repetitive work
But there are also limitations in using event delegation :
focus、blurThese events have no event bubbling mechanism , Therefore, the delegate binding event cannot be performedmousemove、mouseoutSuch an event , Despite the bubbling of events , But we can only calculate the positioning by the position , High consumption of performance , Therefore, it is not suitable for event delegation
边栏推荐
猜你喜欢

实验设计

淘宝助理停用,用大淘营导入数据包上传宝贝提示“主图为必填项,不能为空”是什么原因?如何解决?

Jedis 6 - Introduction and difference between redisson and jedis

Description and implementation of throttling and anti shake

Cluster chat server: how to solve the problem of cross server communication | redis publish subscribe
![[create birthday card application]](/img/56/e04a9a20e181ad7b68b0f2d1d118bc.png)
[create birthday card application]

Day109. Shangyitong: integrate Nacos, hospital list, drop-down list query, hospital online function, hospital details query

宇树A1机器狗手势控制
![[mathematical modeling summer training] location of distribution center](/img/d5/c9b4de6750a7ed080c194250629467.png)
[mathematical modeling summer training] location of distribution center

【HiFlow】腾讯云新一代自动化助手,我用它完成了企业疫情提示(无代码)
随机推荐
启牛是什么?请问一下手机开户股票开户安全吗?
SQL注入攻击
MySQL如何对SQL做prepare预处理(解决IN查询SQL预处理仅能查询出一条记录的问题)
PCL出错:error C2589“(“:“::“右边的非法标记)
大淘营批量采集商品,如何将未上传的宝贝保存下来等后面再导入采集上传
Basic knowledge of mobile phone testing
宇树A1机器狗手势控制
[create birthday card application]
Redis常用命令对应到Redisson对象操作
Several methods of obtaining longitude and latitude by cesium
Real time monitoring of MySQL database changes_ Synchronize data_ Learn about canal_--- Canal work notes 001
U++ learning notes tsubclassof()
Introduction to database system fifth edition after class exercises - Chapter 1 Introduction
合宙ESP32C3硬件配置信息串口打印输出
Hezhou esp32c3 hardware configuration information serial port printout
Openlayers instances advanced mapbox vector tiles advanced mapbox vector maps
【愚公系列】2022年06月 .NET架构班 084-微服务专题 Abp vNext微服务通信
DBSCAN point cloud clustering
VLAN comprehensive experiment
&9 nodemon自动重启工具