In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "JavaScript event capture Bubble Analysis". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "JavaScript event capture bubble analysis" bar!
I. event flow
In JavaScript, the event flow refers to the DOM event flow.
1. Concept
The propagation process of the event is the DOM event stream.
The propagation process of event objects in DOM is called "event flow".
For example: in the case of turning on the computer, first of all, do you have to find your computer, then find your boot button, and finally press the boot button with your hand. Finish turning on the computer. This whole process is called event flow.
2. DOM event flow
There is also a process for DOM events. There are three stages from the event trigger to the event response.
Event capture phase
Be in the target stage
Event bubbling stage
In the above example, the process of turning on the computer is like the event flow in JavaScript. The process of finding the boot button is the process of event capture. After you find the boot button, then press the boot button with your hand. The process of choosing to press the boot button with your hand is to press the boot button at the target stage, and the computer starts to boot, which is the bubbling of the event. The order is to capture before bubbling.
Now that we know the source of the event, let's take a look at its three processes.
Event capture:
Note: because event capture is not supported by older browsers (IE8 and below), event handlers are usually triggered during the bubbling phase in practice.
Event capture is the first step in the event flow
When the DOM event is triggered (the element that triggered the DOM event is called the event source), the browser propagates the event from the outside to the inside from the root node. That is, the event flows from the root node of the document to the target object node. On the way, it passes through various levels of DOM nodes, and finally to the target node to complete the event capture.
Target phase:
When the event reaches the target node, the event enters the target phase. The event is triggered on the target node.
Is that the event propagates to the lowest element that triggers the event.
Event bubbling:
Event bubbling is contrary to the order of event capture. The order of event capture is from outside to inside, and event bubbling is from inside to outside.
When the event propagates to the target stage, the element in the target stage will propagate the received time upward, that is, along the path of event capture, it propagates once in the opposite direction, and propagates to the ancestor element of the element step by step. Until the window object.
Looking at an example, clicking box3 will trigger click events for box2 and box1.
JavaScript event bubbling # box1 {background: blueviolet;} # box2 {background: aquamarine;} # box3 {background: tomato;} div {padding: 40px; margin: auto } _ window.onload = function () {const box1 = document.getElementById ('box1') const box2 = document.getElementById (' box2') const box3 = document.getElementById ('box3') box1.onclick = sayBox1; box2.onclick = sayBox2; box3.onclick = sayBox3 Function sayBox3 () {console.log ('you ordered the innermost box');} function sayBox2 () {console.log (' you ordered the outermost box');} function sayBox1 () {console.log ('you ordered the outermost box') }}
At this time, the propagation order of click capture is:
Window-> document->->
At this time, the spread order of click bubbling is as follows:
->-> document-> window
Modern browsers start capturing events from the window object, and the last stop for bubbling is the window object. IE8 and the following browsers will only bubble to the document object.
Event bubbling: it is determined by the HTML structure of the element, not by its position on the page, so even if you use positioning or floating to take the element out of the scope of the parent element, it still bubbles when you click the element.
Now that we know the three stages of the event flow, what can we do with this feature?
II. Event delegation
Imagine a scenario where you have a bunch of tags under one tag and you need to bind onclick events to all tags. We can use loops to solve this problem, but is there any easier way?
We can add an onclick event to these common parent elements, so when any tag in it triggers the onclick event, the onclick event will be propagated and processed through the bubbling mechanism. This behavior is called event delegation, which uses event bubbling to delegate the event to the.
You can also use event capture to delegate events. The usage is the same, but in reverse order.
Item 1 item 2 item 3...
It may still be a little difficult to understand, simply to use event bubbling to delegate an event on an element to his parent.
To cite an example in life, when the Singles Day express arrives, the delivery needs to be delivered door-to-door, so the efficiency is slow. The little brother thought of a way to put all the deliveries of a community in the express post station in the community to entrust the event of delivery, and the recipients of the district can pick up their own delivery through the pick-up code to the delivery station.
Here, the courier is an event, and the recipient is the element that responds to the event, and the post station is equivalent to the agent element. The recipient takes advantage of the harvest code to pick up the courier in the post station is the event execution. The agent element determines that the current response event matches the specific event triggered.
But what good is it?
1. Advantages of event delegation
Event delegation has two advantages
Reduce memory consumption
Dynamic binding event
Reduce memory consumption and optimize page performance
In JavaScript, every event handler is an object, which will occupy page memory. The more objects in memory, the worse the performance of the page, and the operation of DOM will cause the browser to rearrange and redraw the page (if this is not clear, partners can understand the rendering process of the page), too many DOM operations will affect the performance of the page. One of the main ideas of performance optimization is to minimize rearrangement and redrawing, that is, to reduce DOM operations.
In the above example of binding onclick events to a tag, you don't have to bind a function to each by using an event delegate, but only once. When the number of li is large, it can undoubtedly reduce a lot of memory consumption and save efficiency.
Dynamic binding event:
If the child element is uncertain or dynamically generated, you can replace the listening child element by listening to the parent element.
Again, in the example of tag binding onclick event above, most of the time, the number of these tags is not fixed, and some tags will be added or deleted according to the user's operation. Each time you add or remove a tag, you re-bind or unbind the corresponding event to the new or deleted element.
You can use an event delegate without having to operate it once for each, but only to bind it once, because the event is bound on, and the element is not affected. The execution to the element is matched in the process of actually responding to the execution of the event function, so using the event delegate can reduce a lot of repetitive work in the case of dynamically binding events.
We know the advantages of event delegation, so how to use it?
2. The use of event delegation
The addEventListener () method, event listener, is required for the use of event delegates.
Method registers the specified listener with the object that calls the function, and when the object triggers the specified event, the specified callback function is executed.
Usage:
Element.addEventListener (eventType, function, useCapture); required / optional parameters describe the type of event that eventType is required to specify. Function is required to specify the callback function after the event is triggered. The useCapture option specifies whether the event is executed in the capture phase or in the bubbling phase.
The third parameter, useCapture, is of Boolean type, and the default value is false
True-indicates that the event executes during the capture phase
False- indicates that the event executes during the bubbling phase
Look at the following example:
JavaScript event delegation item 1 item 2 item 3 item 4 const myUl = document.getElementsByTagName ("ul") [0]; myUl.addEventListener ("click", myUlFn); function myUlFn (e) {if (e.target.tagName.toLowerCase () = 'li') {/ / determine whether it is the desired element console.log (`you clicked on ${e.target.innerText} `);}}
Note: this is the general event delegation method, but there is a problem with this writing, that is, when there is a child element in _ _, clicking on this child element will not trigger the event. This problem is a pit.
Event bubbling can be useful sometimes, but it can also be annoying. Can you cancel it when you don't need it?
III. Prohibition of event bubbling and capture
Note: not all events will bubble, such as focus,blur,change,submit,reset,select and so on.
The method stopPropagation () can be used to suppress bubbling and capture.
StopPropagation () prevents further propagation of the current event during the capture and bubbling phase.
This is the bubbling method that prevents the event from bubbling, but the default event is still executed when you call this method.
If you click on an a tag, the a tag will jump.
It is also easy to use, with no return values and no parameters.
Event.stopPropagation ()
Take a look at the following example, which is a slight modification based on the event bubbling example above
Const box1 = document.getElementById ('box1') const box2 = document.getElementById (' box2') const box3 = document.getElementById ('box3') box1.onclick = sayBox1; box2.onclick = sayBox2; box3.onclick = sayBox3; function sayBox3 () {console.log (' you ordered the innermost box') } function sayBox2 (e) {console.log ('you clicked the middle box'); e.stopPropagation (); / / prohibit event capture and bubbling} function sayBox1 () {console.log (' you clicked the outermost box');}
When the event bubbles to box2, the in function sayBox2 is called, and e.stopPropagation () is called; it stops bubbling.
At this point, I believe you have a deeper understanding of "JavaScript event capture bubbling Analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.