JavaScript event bubbling details and trapping, blocking methods _javascript tips

Source: Internet
Author: User

I. Sequence of occurrences

The origin of this problem is very simple, assuming you have another element nested within one element

Copy Code code as follows:

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

: And both have an OnClick event handler function (event handler). If the user clicks Element 2, the click events for element 1 and element 2 are triggered. But which event was triggered first? Which event handler function will be executed first? In other words, what is the order of events?

Two types of models

Predictably, Netscape and Microsoft had two very different ways of dealing with the "awful" (Browser wars) days:

Netscape advocates that element 1 occurs first, and that the sequence of events is called the capture type
Microsoft maintains the priority of element 2, a sequence of events called bubbling
These two sequence of events are diametrically opposed. The Explorer browser only supports bubbling events, both Mozilla,opera7 and Konqueror support. And the older opera and icab don't support either.

Iii. Captured Events

When you are using a Catch type event

Copy Code code as follows:

| |
---------------| |-----------------
|                element1 | | |
| -----------| |-----------     |
|     |element2 \/| |
| -------------------------     |
| Event Capturing |
-----------------------------------

: The event handler function for element 1 is first triggered, and the event handler for element 2 is finally triggered

Bubble Type Event

When you use a bubble type event

Copy Code code as follows:

/ \
---------------| |-----------------
|                element1 | | |
| -----------| |-----------     |
|          |element2 | |     | |
| -------------------------     |
| Event Bubbling |
-----------------------------------

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

V. The model of the Consortium

The consortium wisely chose an option in the battle. Any event that occurs in the model of the event is first entered into the capture phase until the target element is reached and then into the bubbling phase

Copy Code code as follows:

| | / \
-----------------| |--| |-----------------
|  element1 | |                | | |
| -------------| |--| |-----------     |
|          |element2 \/| |     | |
| --------------------------------     |
| The event model of the Consortium |
------------------------------------------

For a web developer, you can choose whether to bind the event handler in the capture or bubbling phase, which is implemented through the AddEventListener () method, and if the last argument of this function is true, the function is bound to be captured in the capture phase, or false, Bind functions in the bubbling phase.

Suppose you're going to do

Copy Code code as follows:

Element1.addeventlistener (' click ', dosomething2,true)

Element2.addeventlistener (' click ', Dosomething,false)

If the user clicks Element 2, the following occurs:

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

1. The Click event first enters the capture phase (gradually approaching the direction of element 2). See if there are any of the ancestor elements in element 2 that have the onclick handler function in the capture phase.
2. Found that element 1 had one, so DoSomething2 was executed
3. The event checks to the target itself (element 2), and no more processing functions are found in the capture phase. The event begins to enter the bubbling phase, assuming the dosomething (), which is bound to the element 2 bubbling phase of the function.
4. Events move away from element 2 to see if any ancestor elements bind a handler function in the bubbling phase. There is no such situation, so nothing has happened
The opposite is the case:

Copy Code code as follows:

Element1.addeventlistener (' click ', Dosomething2,false)

Element2.addeventlistener (' click ', Dosomething,false)


Now if the user clicks Element 2, it will happen:

1. Click the event to enter the capture phase. To see if there is an onclick handler in the capture phase of the ancestor element 2, the result is nothing.
2. Event check to target yourself. The event begins to enter the bubbling phase and performs a function bound to the element 2 bubbling phase. DoSomething ()
3. The event begins to move away from the target, checking that the ancestor element of element 2 has a handler that is bound in the bubbling phase
4. A doSomething2 () of element 1 was found to be executed

Vi. compatibility and traditional models

In browsers that support the Web-consortium DOM (Document Object model), the traditional event-binding approach is

Copy Code code as follows:
Element1.onclick = doSomething2;

Default is considered to be binding in the bubbling phase

Vii. using bubbling Events

Few developers are aware of the use of bubbling events or capture-type events. In the Web page they made today, there is no need for an event to be handled by several functions because of bubbling. But sometimes users are often confused because there are many situations after they have clicked only one mouse (multiple functions are executed because of bubbling). And in most cases you want your processing functions to be independent of each other. When a user clicks on an element, what happens, clicks on another element, and corresponds to what happens, independent of each other, not because of the bubbling chain.

Eight, it's been happening.

The first thing you need to understand is that event capture or bubbling is happening all the time. If you give the entire page document a definition of a universal onclick handler function

Copy Code code as follows:

Document.onclick = dosomething;
if (document.captureevents) document.captureevents (Event.click);

Clicking on any element on the page will eventually bubble to the top document layer of the page, thus triggering that generic handler unless the previous handler explicitly indicates that the bubble is terminated so that it does not propagate to the entire document level


Add to the second sentence of the above code:

>>> first say IE
Object.setcapture () When an object is SetCapture, his method is inherited to the entire document for capture.
When you do not need to inherit the method to the entire document capture, use the Object.releasecapture ()
>>>others
Mozilla also has similar functionality, with a slightly different approach
Window.captureevents (Event.eventtype)
Window.releaseevents (Event.eventtype)
>>>example

Copy Code code as follows:
If only the following sentence, then click obj will trigger click Obj.onclick = function () {alert ("Something")}
If you add the following sentence, the method is inherited to document (or window, different browsers) to capture
Obj.captureevents (Event.click); Ff
Obj.setcapture ()//ie

Ix. usage

Because any event propagation terminates at the page document (this top-level), which makes the default event handler possible, suppose you have a page

Copy Code code as follows:

------------------------------------
| Document |
| ---------------  ------------  |
| |  element1 | |  Element2 | |
| ---------------  ------------  |
| |
------------------------------------
Element1.onclick = dosomething;
Element2.onclick = dosomething;
Document.onclick = defaultfunction;

Now if the user clicks Element 1 or Element 2,dosomething () will be executed. If you prefer, if you don't want to let the event bubble up to the execution defaultfunction (), you can stop the event bubbling up to propagate here. But if the user clicks on the other part of the page, Defaultfunction () will still be executed. This kind of effect may sometimes be used on.

Set the page--the processing function has a larger area of trigger, which is required in the drag-and-drop script. Generally speaking, the occurrence of a MouseDown event on an element layer means that the element is selected and enables it to respond to MouseMove events. Although MouseDown is usually bound to this element layer to avoid browser bugs, the scope of the other two event functions must be the entire page (?). )

Remember that the first rule of browserology is that everything is possible (anything can happen) and is at least a little prepared. So what's likely to happen is that when the user drags the mouse over the page, the script does not react in a large scale so that the mouse stops at the element layer.

1. If the onmouseover processing function is bound to the element layer, this element layer will not react to the movement of the mouse any more, which will make the user feel strange
2. If the onmouseup processing function is bound to the element layer, the event cannot be triggered, and the result is that the element layer continues to react to the mouse movement after the user wants to drop the element layer. This can cause (users) more confusion (?). )

So in this case, event bubbling is very useful because putting your processing functions on the page layer guarantees that they will always be executed.

Ten, turn it Off (block event bubbling)

But generally, you will want to turn off all bubbles and capture to ensure that the function does not disturb each other. In addition, if your document structure is quite complex (many of the table are nested or so on), you will also turn off bubbling to conserve system resources. At this point, the browser has to check each ancestor of the target element to see if it has a handler function. Even if one did not find it, just the search also took a lot of time

In the Microsoft model, you have to set the Cancelbubble property of the event to True

Copy Code code as follows:
Window.event.cancelBubble = True

You must invoke the Stoppropagation () method of the event in the Consortium model
Copy Code code as follows:
E.stoppropagation ()

This prevents all bubbling from spreading outward. This should be done as a cross-browser solution:
Copy Code code as follows:

function DoSomething (e)

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

E.cancelbubble = true;

if (e.stoppropagation) e.stoppropagation ();

}

Setting cancelbubble in browsers that support cancelbubble properties is harmless. The browser will shrug and create this property. Of course this doesn't really cancel bubbles, but at least it guarantees that the command is safe and correct.

Xi. Currenttarget

As we've seen before, an event with target or srcelement attribute is used to indicate exactly which target element the event occurred on (that is, the element that the user initially clicked on). In our example is element 2, because we clicked it.

It is important to understand that the target element in the capture or bubbling phase is invariant and is always associated with element 2.

But suppose we bind the following functions

Copy Code code as follows:
Element1.onclick = dosomething;

Element2.onclick = dosomething;


If the user clicks Element 2, dosomething () is executed two times. But how do you know which HTML element is responding to this event? Target/srcelement also gave no clues, but people were always more inclined to element 2 because it was the cause of the event (because the user clicked it).
To solve this problem, the Currenttarget attribute is added to the consortium, which points to the element that is handling the event: That's exactly what we need. Unfortunately, there is no similar attribute in the Microsoft model.
You can also use the "this" keyword. In the example above, it is equivalent to the HTML element in which the event is being processed, like Currenttarget.

12, the problem of the Microsoft model

But when you use the Microsoft event-binding model, the This keyword does not correspond to HTML elements. Lenovo lacks a Microsoft model similar to the Currenttarget attribute (? )--You do this by following the above code:

Copy Code code as follows:
Element1.attachevent (' onclick ', dosomething)

Element2.attachevent (' onclick ', dosomething)


You don't know exactly which HTML element is responsible for handling events, which is the most serious problem with the Microsoft event-binding model, which is why I never used it, even if I was developing an application for IE only under Windows.

I would like to be able to add currenttarget similar attributes as soon as possible--or follow the standard? This information is needed by web developers

Postscript:

Because there is no actual combat JavaScript, so this article some places I am not very understanding, can only be hard to translate out, such as talking about the effect of the drag, if you have any additional and questions you can leave a message to me, thank you support!

PS: Here again for you to recommend a JS event on the online query tool, summed up JS commonly used event types and function functions:

JavaScript event and Feature description encyclopedia:

Http://tools.jb51.net/table/javascript_event

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.