当前位置:网站首页>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
边栏推荐
- 集群聊天服务器:工程目录的创建
- & 9 nodemon automatic restart tool
- 集群聊天服务器:如何解决跨服务器通信问题 | redis发布-订阅
- A stack of digital robots were selected in Gartner's China AI market guide
- Distributed transaction scheme: best effort notification scheme
- Cluster chat server: chatservice business layer
- U++学习笔记 TSubclassOf()
- 寻找消失的类名
- jedis 6---redisson和jedis的入门和不同
- 节流和防抖的说明和实现
猜你喜欢
随机推荐
集群聊天服务器:数据库表的设计
Cluster chat server: chatservice business layer
集群聊天服务器:如何解决跨服务器通信问题 | redis发布-订阅
Boost Filesystem使用手册
节流和防抖的说明和实现
Chapter1 data cleaning
分布式能源的不确定性——风速测试(Matlab代码实现)
Construction and application progress of ten billion level knowledge map of meituan brain
U++ events
集群聊天服務器:數據庫錶的設計
Customer exit variable in query
Still have 1 requests outstanding when connection from slaveX/X.X.X.X:33202 is closed
Pulsar open source message queue_ Understand pulsar --- pulsar work notes 001
Cluster chat server: creation of project directory
Basic character axis binding and mapping binding of u++ learning notes
U++ learning notes control object scale
pulsar开源消息队列_了解Pulsar---Pulsar工作笔记001
Payment products and their usage scenarios
Openlayers instances advanced mapbox vector tiles advanced mapbox vector maps
Redis常用命令对应到Redisson对象操作









