A vivid and detailed explanation of the bubbling and capturing of JavaScript, packet Understanding (RPM)

Source: Internet
Author: User

Foreword: Although proficient in jquery, but not very familiar with its prototype JavaScript, recently encountered some difficulties in learning JavaScript, such as bubbling and capturing, many times mentioned, but do not know exactly where to apply. Find some good articles for your doubts and share them here.

Quirksmode a series of articles are good, easy to understand, this article is just a series of one, there is a chance to translate JavaScript this series are translated to everyone.

The original address is http://www.quirksmode.org/js/events_order.html here, the sentence is marked "(? "I am not very understanding of this sentence, it may be wrong." Official start:

The order in which events occur

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

-----------------------------------| 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 is triggered first? Which event handler function will be executed first? In other words, what is the order in which events occur?

Two types of models

Unsurprisingly, Netscape and Microsoft have two very different ways of dealing with the "terrible" (Browser wars) days:

    • Netscape asserts that element 1 events occur first, and this sequence of events is called the capture type
    • Microsoft retains the priority of element 2, a sequence of events called bubbling

The sequence of the two events is diametrically opposed. The Explorer browser only supports bubbling events, both Mozilla,opera7 and Konqueror support. And the older opera and Icab both don't support

Capture-type Events

When you use capture-type events

               | |---------------| |-----------------| Element1     |   | | | -----------| |-----------     ||   | Element2  \/          |   | | -------------------------     ||        Event Capturing          |-----------------------------------

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

Bubble Type Event

When you use bubbling events

               / ---------------| |-----------------| Element1     |   | | | -----------| |-----------     ||   | Element2 | | | |     |   -------------------------     ||        Event Bubbling           |-----------------------------------

: The handler function for element 2 is first triggered, element 1 is followed by

the Model

The wisdom of the market has chosen a choice in this battle. Any event that occurs in the event model is the first to enter the capture phase until the target element is reached and then into the bubbling phase

                 | |  / -----------------| |--| |-----------------| element1 | | | | |                |   -------------| |--| |-----------     ||   | Element2    \/| | | |     |   --------------------------------     ||        Event Model                 |------------------------------------------

For a web developer, you can choose to bind the event handler in the capture or bubbling phase, which is implemented by the AddEventListener () method, if the last parameter of the function is true, the function is bound in the capture phase, and vice versa, The function is bound during the bubbling phase.

Suppose you're going to do

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, from outside to inside, gradually approaching the main element of the trigger, and then leaving in reverse)

    1. Click the event to begin the capture phase first (gradually approaching the direction of element 2). View whether there is an onclick handler function in the ancestor element of element 2 in the capture phase
    2. found that element 1 had one, so DoSomething2 was executed
    3. The event is checked to the target itself (element 2), and no more processing functions are found in the capture phase. The event begins to go into the bubbling phase, assuming that dosomething (), a function bound to the bubbling phase of element 2, is taken for granted.
    4. event to the direction away from element 2 to see if any ancestor elements are bound to a handler function during the bubbling phase. There was no such situation, so nothing happened.

The opposite is the case:

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

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

Now if the user clicks on element 2 it will happen:

    1. Click events to enter the capture phase. See if there is an onclick handler function in the ancestor element of element 2 in the capture phase, resulting in nothing
    2. The event is checked to the target itself. The event begins to enter the bubbling phase and performs functions that are bound to the bubbling phase of element 2. DoSomething ()
    3. The event starts away from the target, examining whether the ancestor element of element 2 has a handler function bound in the bubbling phase.
    4. Found one, so the doSomething2 () of element 1 is executed

Compatibility and Legacy modes

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

Element1.onclick = doSomething2;

Default is considered to be bound to the bubbling phase

Using bubbling Events

Few developers are aware of the use of bubbling events or captured events. In the Web pages they make today, it is not necessary to let an event be handled by several functions because of bubbling. But sometimes users are often confused because there are a number of things that happen after they click the mouse only once (multiple functions are executed because of bubbling). In most cases, you want your processing functions to be independent of each other. When the 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.

It's been happening.

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

Document.onclick = dosomething;

if (document.captureevents) document.captureevents (Event.click);

The second sentence I do not know what the meaning, beginners, hope that some capable can explain

Clicking on any element's click event on the page will eventually bubble up to the top document layer of the page, 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 plane

Usage (this section translation is not good, because there is no actual combat, I am not very understanding, can be added in the message, I will update)

Because any event propagation terminates at the page document (the highest level), this makes the default event handler possible, assuming you have such a page

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

Now if the user clicks on element 1 or the element 2,dosomething () will be executed. If you wish, if you do not want the event to bubble up to the execution of defaultfunction (), you can stop the event bubbling up and propagate up here. However, if the user clicks on other parts of the page, Defaultfunction () will still be executed. Such effects may sometimes be used.

Settings page--Makes the processing function have a large range of trigger area, in the "Drag effect" script is necessary. In general, the occurrence of an MouseDown event on an element layer means that this element is selected and enables it 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 Browser science (browserology) is: Everything is possible (anything can happen), and at least when you are prepared. So it's possible that when a user drags a page and moves his mouse over a large screen, the script doesn't react so much that the mouse stops at the element level.

    • If the onmouseover handler is bound to the element layer, the element layer will no longer react to the mouse movement, which makes the user feel strange
    • If the onmouseup handler is bound to the element layer and the event cannot be triggered, the result is that the element layer continues to react to the mouse movement after the user wants to drop the element layer. This will cause (the user) more confusion (?). )

So in this case, event bubbling is very useful because putting your handler on the page layer ensures that they can be executed all the time.

Turn it off.

But in general, you'll want to turn off all the bubbles and captures to ensure that the functions don't disturb each other. In addition, if your document structure is quite complex (many table nesting or the like), you can 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 is not found, just the search also takes a lot of time

In Microsoft's model, you must set the Cancelbubble property of the event to True

Window.event.cancelBubble = True

You must invoke the Stoppropagation () method of the event in the model

E.stoppropagation ()

This will prevent all bubbling from spreading outward. And as a cross-browser solution, this should be the scenario:

function DoSomething (e)

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

E.cancelbubble = true;

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

}

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

Currenttarget

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

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

But suppose we bind the following function

Element1.onclick = dosomething;

Element2.onclick = dosomething;

If the user clicks on element 2, dosomething () is executed two times. But how do you know which HTML element is responding to this event? Target/srcelement also does not give clues, but people are always more inclined to element 2, because it is the cause of the event (because the user clicked on it).

To solve this problem, the Currenttarget this property, which points to the element that is handling the event: This is exactly what we need. Unfortunately, there are no similar attributes in the Microsoft model.

You can also use the "this" keyword. In the example above, it is equivalent to the HTML element that is processing the event, just like Currenttarget.

Problems with Microsoft Models

But when you use the Microsoft Event binding model, the This keyword is not the equivalent of an HTML element. Lenovo lacks a Microsoft model like the Currenttarget attribute (? )--by following the code above, you would mean:

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 use it, even if I'm developing an app for Windows-only ie.

I want to be able to increase currenttarget similar properties as soon as possible--or follow the standard? Web developers need this information

Postscript:

Because there is no actual combat JavaScript, so this article some places I do not understand, can only be hard to translate out, such as talk about the effect of the paragraph dragged, if you have any supplementary and questions can leave a message to me, thank you support!

A vivid and detailed explanation of the bubbling and capturing of JavaScript, packet Understanding (RPM)

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.