Home > Web Front-end > JS Tutorial > Detailed explanation of javascript event bubbling and methods of capturing and blocking_javascript skills

Detailed explanation of javascript event bubbling and methods of capturing and blocking_javascript skills

WBOY
Release: 2016-05-16 16:52:37
Original
946 people have browsed it

1. The sequence of events

The origin of this problem is very simple, suppose you have an element nested within another element

Copy code Code As follows:

----------------------------------
| element1                                                                                      | ------------------ |

--------------------- -----------

: And both have an onClick event handler. If the user clicks on element 2, the click events of both element 1 and element 2 will be triggered. But which event is triggered first? Which event handler function will be executed first? In other words, what was the exact sequence of events?

2. Two models

As expected, Netscape and Microsoft had two very different approaches to dealing with those days of the "browser wars":

Netscape advocates that the event of element 1 occurs first. This order of event occurrence is called the capturing type.

Microsoft maintains that element 2 has priority. This order of events is called the bubbling type.

Both of them The sequence of events is diametrically opposed. Explorer browser only supports bubbling events, Mozilla, Opera7 and Konqueror support both. The older opera and iCab do not support either



3. Capture events

When you use capturing events


---------------| |------------------
| element1 | | |
| --- --------| |----------- |
| |element2 / |
| --------------- ---------- |
| Event CAPTURING |
----------------------------- ------

: The event handler of element 1 is triggered first, and the event handler of element 2 is triggered last

4. Bubbling events

When you use bubbling events


Copy the code The code is as follows:                
---------------| |------------------
| element1 | | |
| - ----------| |----------- |
| |element2 | | |
| ---------- ------------- |
| Event BUBBLING |
-------------------------- ---------

: The processing function of element 2 is triggered first, followed by element 1

5. W3C Model

W3c wisely chose the right solution in this battle. Any event that occurs in the w3c event model first enters the capture phase until it reaches the target element, and then enters the bubbling phase


Copy code The code is as follows:

                                                               --
| element1 | | | | |
| -------------| |--| |----------| |
| |element2 / | | |
| -------------------------------- |
| W3C event model |
---------------------------------------------
As a web developer, you can choose whether to bind the event processing function in the capture phase or the bubbling phase. This is achieved through the addEventListener() method. If the last parameter of this function is true, then in the capture phase Phase binding function, otherwise false, binds the function in the bubbling phase.
Suppose you want to do


Copy code The code is as follows:
element1.addEventListener(' click',doSomething2,true)
element2.addEventListener('click',doSomething,false)

If the user clicks on element 2, what happens next:

(The event is like a tourist here, traveling from outside to inside, gradually approaching the main element that was triggered, and then leaving in the opposite direction)

1. The click event first enters the capture phase (gradually approaching the direction of element 2). Check whether any of the ancestor elements of element 2 has an onclick handler in the capture phase

2. It is found that element 1 has one, so doSomething2 is executed
3. The event checks the target itself (element 2), but there is no onclick handler in the capture phase Found more processing functions. The event begins to enter the bubbling stage, and doSomething() is executed naturally, which is a function bound to the bubbling stage of element 2.
4. The event moves away from element 2 to see if any ancestor element has a handler bound to it during the bubbling phase. There is no such case, so nothing happens
The opposite case is:

Copy the codeThe code is as follows:
element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)

Now if the user clicks on element 2 it will happen:
1. Click the event to enter the capture phase. Check whether any of the ancestor elements of element 2 has an onclick handler in the capture phase, and find nothing

2. The event detects the target itself. The event begins to enter the bubbling phase, and the function bound to the bubbling phase of element 2 is executed. doSomething()
3. The event starts to move away from the target. Check whether any of the ancestor elements of element 2 has a handler function bound to it during the bubbling phase. 4. One is found, so doSomething2() of element 1 is executed.

6. Compatibility and traditional mode

In browsers that support w3c dom (Document Object Model), the traditional event binding method is


Copy code The code is as follows: element1.onclick = doSomething2;
is considered to be bound to the bubbling stage by default

7. Use bubbling events

Few developers will consciously use bubbling events or capturing events. In the web pages they make today, there is no need for an event to be handled by several functions because it bubbles up. But sometimes users are often confused because after they clicked the mouse only once many things happen (multiple functions are executed because of bubbling). In most cases you still want your processing functions to be independent of each other. When the user clicks on an element, what happens, and what happens when the user clicks on another element, are independent of each other and not linked by bubbling.

8. It happens all the time

The first thing you need to understand is that event capturing or bubbling is always happening. If you define a general onclick processing function for the entire page document


document.onclick = doSomething;
if (document.captureEvents) document.captureEvents(Event.CLICK);

The click event of clicking any element on the page will eventually bubble up to the highest document layer of the page, thus triggering the general processing function, unless the previous processing function explicitly points out that the bubbling is terminated. Will not be propagated to the entire document level


Addition to the second sentence of the above code:

>>> Let’s talk about IE first
object.setCapture() When an object is setCapture, its method will be inherited to the entire document for capture.
When you do not need to inherit the method to capture the entire document, use object.releaseCapture()
>>>others
Mozilla also has a similar function, the method is slightly different
window.captureEvents (Event.eventType)
window.releaseEvents(Event.eventType)
>>>example

Copy code The code is as follows:
//If there is only the following sentence, then click will be triggered only when obj is clicked obj.onclick = function(){alert("something")}
//If Add the following sentence, the method will be inherited to the document (or window, different browsers are different) to capture
obj.captureEvents(Event.click); //FF
obj.setCapture() // IE

9. Usage

Because any event propagation terminates in the page document (this top level), this makes the default event handler possible, assuming you have a page like this

Copy Code The code is as follows:

------------------------------ --------
| document                                                                   | element1 | | element2 | |
| --------------- ------------ |

----- ----------------------------------
element1.onclick = doSomething;
element2.onclick = doSomething;
document.onclick = defaultFunction;


Now if the user clicks on element 1 or element 2, doSomething() will be executed. If you wish, you can prevent events from bubbling up here if you don't want them to bubble up to defaultFunction(). But if the user clicks elsewhere on the page, defaultFunction() will still be executed. This effect may be useful sometimes.

Settings page - enables the processing function to have a larger trigger area, which is necessary in the "drag effect" script. Generally speaking, the occurrence of a mousedown event on an element layer means that the element is selected and enabled to respond to the mousemove event. Although mousedown is usually bound to this element layer to avoid browser bugs, the scope of the event functions of the other two must be the entire page (?)

Remember the First Law of Browserology: anything can happen, and that’s when you are at least somewhat prepared. So what may happen is that when the user drags and drags, he moves his mouse greatly on the page, but the script cannot respond to the large amplitude, so that the mouse no longer stays on the element layer

1. If the onmouseover handler function is bound to the element layer, this element layer will no longer respond to mouse movement, which will make users feel strange

2. If the onmouseup handler function is bound to the element layer , the event cannot be triggered. The consequence is that after the user wants to drop this element layer, the element layer continues to respond to mouse movement. This will cause more confusion (?)


So in this example, event bubbling is very useful, because placing your handler functions at the page level ensures that they can always be executed

10. Turn it off (to prevent events from bubbling)

But generally, you will want to turn off all bubbling and capturing to ensure that functions do not disturb each other. In addition, if your document structure is quite complex (many tables nested within each other, etc.), you may want to turn off bubbling to save system resources. At this point the browser has to check every ancestor of the target element to see if it has a handler function. Even if no one is found, the search just now still takes a lot of time

In the Microsoft model, you must set the cancelBubble property of the event to true


Copy the code The code is as follows:window.event.cancelBubble = true

In the w3c model you must call the stopPropagation() method of the event
Copy the code The code is as follows:
e.stopPropagation()

This will prevent all bubbling from propagating outward. As a cross-browser solution, this should be done:
Copy the code The code is as follows:

function doSomething(e)

{
  if (!e) var e = window.event;

e.cancelBubble = true;

if (e.stopPropagation) e.stopPropagation();

}

There is no harm in setting cancelBubble in browsers that support the cancelBubble attribute. The browser will shrug and create this attribute. Of course, this doesn’t really cancel bubbling, but it at least ensures that this command is safe and correct

11. currentTarget

As we saw before, an event uses the target or srcElement attribute to indicate which target element the event occurred on (that is, the element the user initially clicked on). In our case it's element 2 because we clicked on it.

It is very important to understand that the target element during the capture or bubbling phase does not change, it is always associated with element 2.

But suppose we bind the following function

Copy code The code is as follows:
element1.onclick = doSomething;

element2.onclick = doSomething;


If the user clicks element 2, doSomething() will be executed twice. But how do you know which html element is responding to this event? target/srcElement also gives no clue, but people will always prefer element 2 because it is the cause of the event (because it is what the user clicked on).
To solve this problem, w3c added the currentTarget attribute, which points to the element that is handling the event: this is exactly what we need. Unfortunately there is no similar attribute in Microsoft models
You can also use the "this" keyword. In the above example, it is equivalent to the html element that is handling the event, like currentTarget.

12. Problems with Microsoft model

But when you use the Microsoft event binding model, the this keyword is not equivalent to the HTML element. Lenovo lacks a Microsoft model similar to the currentTarget property (?) - if you follow the above code, you will mean:

Copy code The code is as follows:
element1.attachEvent('onclick',doSomething)

element2.attachEvent('onclick',doSomething)


You can’t know exactly which HTML element is responsible for handling the event. This is the most serious problem with Microsoft’s event binding model. To me, this This is also the reason why I never use it, even when developing applications only for IE under Windows

I hope to be able to add currentTarget-like properties soon - or follow the standard? Web developers need this information

Postscript:

Because I have never used JavaScript in practice, there are some parts of this article that I don’t quite understand, so I can only translate them abruptly, such as the section about the drag effect. If you have any additions or questions, you can leave a message to me. Thank you for your support!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template