Understanding event Handling in JavaScript prevents bubbling event.stoppropagation ();

Source: Internet
Author: User
Tags event listener

Original address: http://www.cnblogs.com/binyong/articles/1750263.html

This article is very good for understanding JavaScript's event-handling mechanism, and it is reproduced here in full-text for a rainy future.

What is an event?

Event is the heart of the JavaScript app beating and the glue that sticks everything together. Events occur when we interact with certain types of Web pages in the browser. An event might be a user's click on something, a mouse passing through a particular element, or some key pressed on the keyboard. Events can also be something that occurs in a Web browser, such as when a Web page is loaded, or if the user scrolls through the window or changes the window size.

By using JavaScript, you can listen to the occurrence of a particular event and specify that certain events occur to respond to these events.

Today's events

In the long history of evolution, we have said goodbye to inline event handling (using the event handler directly inside the HTML element). Today's event, which is already an important part of the DOM, unfortunately, IE continues to retain its earliest implementation of the event model in IE4.0, the later version of IE did not make too much change, which means IE is still using a proprietary event model (bubbling type), while the other mainstream browser until the DOM Level 3 has been finalized to support the DOM standard event-handling model-capture and bubble type.

The historical reasons are: The Web-based specification does not define any events in DOM Level 1 until DOM level 2, published in November 2000, defines a small subset, and DOM Level 2 provides a more detailed and more granular way to control the events in the page, and finally, the complete event is 2 The 004-year DOM Level 3 rule was finalized. Since IE4 is 1995 launched and has implemented its own event model (bubbling type), there is no DOM standard at the time, but in the future DOM standard specification process has absorbed the IE event model into it.

Currently in addition to IE browser, other mainstream Firefox, Opera,
Safari supports the standard DOM event processing model. IE still uses its own proprietary event model, the bubbling type, and its part of the event model is used by the DOM standard, which is also good for developers, only using
Dom Standard, IE has a common event handling method to effectively cross the browser.

Dom Event Flow

The DOM (Document Object model) structure is a tree structure, and when an HTML element produces an event, the event propagates in a particular order between the element node and the root node, and the node that passes through the path receives the event, which can be called the DOM event stream.

There are two types of event order: event snapping and event bubbling .

Bubbling events (event bubbling)

This is the Internet Explorer to the event model implementation, but also the most easy to understand, at least I feel more in line with the actual. Bubbling, as the name implies, the event goes up like a bubble in the water until the top. From
The DOM tree structure is understood to be that the event is passed from the leaf node to the root node along the ancestor nodes; the arrangement of the HTML elements from the browser interface view is understood to be that the event is passed from the most determined target element with a dependency to the most indeterminate target element. Bubbling technology. The basic idea of bubbling events, Events are based on the target of the most uncertain event, starting from a specific event target.

Capture-type events (event capturing)

The implementation of the Netscape, which is just the opposite of the bubbling type, consists of the topmost element of the DOM tree to the most precise element, the event model for the developer (at least me). is a bit confusing, because intuitive understanding should be like bubbling, and event delivery should start with the most deterministic element, the event-generating element.

DOM-standard event model

We have explained and compared the above two different event models. The DOM standard supports both event models, the capture-type event and the bubbling event , but the captured event occurs first. Both event streams trigger all objects in the DOM, starting with the document object and ending with the Document object (most compliant browsers continue to persist the event as snap/bubbling to the Window object).

The first is the capture pass event, followed by the bubbling pass, so if a handler function registers the listener for the captured event and registers the bubbling event listener, it will be called two times in the DOM event model.

The most unique nature of the DOM standard event model is that text nodes also trigger events (not in IE).

Event delivery

To better illustrate the principle of event flow in the DOM standard, we put it in the "event routing" summary to explain it more specifically.

Obviously, if you add a click event Listener to a hyperlink, the event listener is executed when the link is clicked. However, if you assign the event listener to the P element that contains the link or to the document node at the top of the DOM tree, clicking the link will also trigger the event listener. This is because events not only affect the target elements that are triggered, they also affect all elements along the DOM structure. This is what we all know about the event forwarding .

The principle of event forwarding is clearly pointed out in the event model. Event routing can be divided into 3 phases.

Standard Event-Forwarding mode

(1). During the event capture (capturing) phase, events are forwarded down the DOM tree, each ancestor node of the target node, up to the target node. For example, if a user clicks a hyperlink, the Click event is forwarded from the document node to the HTML element, the BODY element, and the P element that contains the link.

During this process, the browser detects the listener for the event's capture event and runs the event listener.

(2). At the target stage, the browser runs the event listener after it finds the event listener that has been assigned to the target event. The target node is the DOM node that triggers the event. For example, if a user clicks on a hyperlink, the link is the target node (the target node is actually a text node within the hyperlink).

(3). During the bubbling (bubbling) phase, the events are forwarded up the DOM tree, once again accessing the ancestor node of the target element to the document node. Each step in the process. The browser detects event listeners that are not capturing event listeners and executes them.

Not all events will go through the bubbling phase.

All events go through the capture and target stages, but some events skip the bubbling phase. For example, the focus event that gives the element input focus and the Blur event that loses the input focus will not bubble.

Event handle and Event listener

Event handle

The event handle (also known as the event handler function, which the DOM calls the event listener function), is called the event handler function in response to an event
。 Each event corresponds to an event handle, and when the program executes, the corresponding function or statement is assigned to the event handle, and when that event occurs, the browser executes the specified function or statement, which enables the interaction of the Web page content with the user's actions. When the browser detects that an event occurs, it finds the event handle that corresponds to the event, and if so, executes the event handle.

We think the function that responds to the Click event is the OnClick event handler function. Previously, event handlers were allocated in two ways: in JavaScript or in HTML .

If you are assigning event handlers in JavaScript, you need to first obtain a reference to the object to be processed, and then assign the function to the corresponding event handler property, see a simple example:

1 var link=document.getelementbyid ("MyLink");
2 Link.onclick=function () {
3 Alert ("I was clicked!");
4};

From the example we see, we find it easy to use an event handle,
However, the event handler name must be lowercase, and there is only
You cannot assign an event handle to an element until the element is loaded, or there will be an exception.

For document loading techniques, see the article "multiple solutions Loaded by Window.onload ".

If you assign an event handle in HTML, you can set the event handler directly through the HTML attribute, and include the appropriate script as the attribute value, for example:

<a href= "/" onclick= "JavaScript code here" >......</a>

This JavaScript code is similar to assigning CSS properties directly to elements through the HTML style property. This makes the code look like a mess and violates the principle of separating the code that implements the dynamic behavior from the code that displays the static content of the document. From 1998 onwards, this style of writing is obsolete.

The advantages and disadvantages of this traditional event binding technique are obvious:

* Simple and convenient, in the HTML directly write the processing function of the code block, in JS to the element corresponding to the event attribute assigned to the value.

A method supported by the *ie and DOM standards, which is invoked during the event bubbling process in both the IE and DOM standards.

* You can use this reference to register an event's element directly within the processing function block, which refers to the current element.

* To register multiple listeners for an element, you cannot use this method.

Event Listener

In addition to the simple event handles that have been described earlier, most browsers now have more advanced event handlers built into them, that is, event listeners, which are not constrained by the binding of an element to only one event handle.

We already know that the most significant difference between an event handle and an event listener is that you can only plug in one event handle at a time using an event handle, but for an event listener, you may be able to plug in multiple at a time.

Event Listener under IE:

IE provides an own, completely different, and even bug-based event listener, so if you want the script to work properly in this browser, you must use the event listener supported by IE. Also, event listeners in Safari are sometimes a little different.

In IE, each element and window object has two methods: the Attachevent method and the DetachEvent method.

1 element.attachevent ("OnEvent", EventListener);

This method means that in IE, to attach an event handler function to an element's event, you must call the Attachevent method to create an event listener. The Attachevent method allows the outside world to register the element with multiple event listeners.

Attachevent accepts two parameters. The first parameter is the event type name, and the second parameter, EventListener, is the callback handler function. Here to explain, there is a often error in the place, ie under
This is the window object when the this point is no longer an element of the previously registered event, using the Attachevent registered handler function call. Another thing is that the event type name of this method must be prefixed with an "on" (such as onclick).

1 element.attachevent ("OnEvent", EventListener);

To remove the event listeners registered by the previous element, you can use the DetachEvent method to delete the same parameters.

Event listeners under the DOM standard:

In browsers that support the standard event listener, you can use the AddEventListener method for each object that supports events. This method supports both registered bubbling event processing and capture-type event processing. So there is a different way of registering element event listener in IE browser.

1//Standard syntax
2 Element.addeventlistener (' event ', EventListener, usecapture);
3//Default
4 Element.addeventlistener (' event ', EventListener, false);

The AddEventListener method accepts three parameters. The first parameter is the event type name, it is worth noting that here the event type name is different from IE, the event type name does not start with ' on ', the second parameter eventlistener is the callback handler function (that is, listener function); The third parameter indicates whether the processing callback function is called during the capture phase of the event pass or the bubbling phase, usually this parameter is set to False (bubbling when false), and if its value is set to True, then a capture event listener is created.

Removing the registered event listener calls the element's RemoveEventListener method, with the same parameters.

1//Standard syntax
2 Element.removeeventlistener (' event ', EventListener, usecapture);
3//Default
4 Element.removeeventlistener (' event ', EventListener, false);

The event handlers that are added through the AddEventListener method must be removed by using the RemoveEventListener method. It also requires that the parameters be exactly the same as the parameters of the AddEventListener method when the event handler is added (including the usecapture parameter), otherwise the event handler will not be successfully deleted.

Cross-browser registration and removal of element event listener scenarios

We now know that for browsers that support the AddEventListener method, the AddEventListener method needs to be called whenever an event listener script is required, and for IE browsers that do not support this method, You need to call the Attachevent method when using event listeners. It is not difficult to make sure that the browser is using the correct method, but only through a if-else statement to detect whether the AddEventListener method or Attachevent method is present in the current browser.

This way, you can implement a cross-browser registration and removal element Event listener scenario:

1 var eventutil = {
2//Registration
3 Addhandler:function (element, type, handler) {
4 if (Element.addeventlistener) {
5 Element.addeventlistener (type, handler, false);
6} else if (element.attachevent) {
7 element.attachevent ("on" + type, handler);
8} else {
9 element["on" + type] = handler;
10}
11},
12//Remove Registration
Removehandler:function (element, type, handler) {
if (Element.removeeventlistener) {
Element.removeeventlistener (type, handler, false);
+ Else if (element.detachevent) {
Element.detachevent ("On" + type, handler);
+} else {
Element["on" + type] = NULL;
20}
21}
22};

Event object reference

To better handle events, you can take different actions depending on the specific properties of the event that occurs.

Like the event model, IE and other browser processing methods differ: IE uses a global event object called event to process the object (it can be found in the global variable window.event), and all other browsers adopt the method of the Web recommendation, is passed using a separate parameter that contains the event object.

When you implement such a feature across browsers, the most common problem is getting a reference to the event itself and getting a reference to the target element of the event.

The following code solves this problem for you:

1 var eventutil ={
2 Getevent:function (event) {
3 return event? Event:window.event;
4},
5 Gettarget:function (Event) {
6 Return Event.target | | Event.srcelement;
7}
8};

Default behavior for stopping event bubbling and blocking events

The two concepts of stop event bubbling and block browser default behavior are important, and they are useful for complex application processing.

1. Stop event bubbling

Stop event bubbling refers to stopping the further passing of bubbling events (canceling event delivery, not just stopping the bubbling events common to the IE and DOM standards, but also stopping the capture-type event that supports the DOM standard browser, using the Toppropagation () method). For example, in a bubbling event pass, the event listener for document on the upper level no longer receives notification and is no longer processed after the body handles the stop event delivery.

2. Default behavior for blocking events

The default behavior of a stop event is that the browser performs the default action associated with the event (if such an action exists) after the event is passed and processed. For example, if the input type attribute in the form is "submit", the form will be submitted automatically when the event is propagated after the click. For example, when the INPUT element's KeyDown event occurs and is processed, the browser will automatically append the characters typed by the user to the value of the INPUT element by default.

How to stop event bubbling :

Under IE, by setting the cancelbubble of the event object to True.

1 function Somehandle () {
2 window.event.cancelBubble = true;
3}

The DOM standard is done by invoking the Stoppropagation () method of the event object.

1 function Somehandle (event) {
2 event.stoppropagation ();
3}

As a result, cross-browser stop events are delivered in the following ways:

1 function Somehandle (event) {
2 event = Event | | window.event;
3 if (event.stoppropagation) {
4 event.stoppropagation ();
5}else {
6 event.cancelbubble = true;
7}
8}

How to handle the default behavior of blocking events

Just like the event model and event object differences, the default behavior of blocking events in IE and all other browsers is different.

Under IE, by setting the returnvalue of the event object to False.

1 function Somehandle () {
2 Window.event.returnValue = false;
3}

The DOM standard is done by invoking the Preventdefault () method of the event object.

1 function Somehandle (event) {
2 Event.preventdefault ();
3}

Because of this, the default way to handle cross-browser cancellation events is:

1 function Somehandle (event) {
2 event = Event | | window.event;
3 if (Event.preventdefault) {
4 Event.preventdefault ();
5}else{
6 event.returnvalue = false;
7}
8}

Full event-handling compatibility function

1 var eventutil = {
2 addhandler:function (element, type, handler) {
3 if (Element.addeventlistener) {
4 Element.addeventlistener (type, handler, false);
5} else if (element.attachevent) {
6 element.attachevent ("on" + type, handler);
7} else {
8 element["on" + type] = handler;
9}
10},
Removehandler:function (element, type, handler) {
if (Element.removeeventlistener) {
Element.removeeventlistener (type, handler, false);
+ Else if (element.detachevent) {
Element.detachevent ("On" + type, handler);
-} else {
Element["on" + type] = NULL;
18}
19},
Getevent:function (event) {
Return event? Event:window.event;
22},
Gettarget:function (event) {
return Event.target | | Event.srcelement;
25},
Preventdefault:function (event) {
if (Event.preventdefault) {
Event.preventdefault ();
} else {
Event.returnvalue = false;
31}
32},
Stoppropagation:function (event) {
if (event.stoppropagation) {
Event.stoppropagation ();
(+)} else {
PNS event.cancelbubble = true;
38}
39};

The application of capture-type event model and bubble-type event model

The standard event model gives us two scenarios where many friends may not be able to tell the difference between these two different models, and why not just take a model.
In this case, the IE browser discussion (ie only one, cannot choose) what kind of event model is appropriate.

1. Capture-type applications

Capture event delivery is performed by the most imprecise ancestor element to the most accurate event source element, and is passed in a similar way to the global shortcut key in the operating system as the application shortcut key. When a system combination key occurs, if the note
The system global shortcut Listener, the event is first captured by the operating system layer, the global listener is notified before the application shortcut key listener, that is, the global first gain control, it has the right to prevent the event of the
One-step delivery. So the capture-type event model is suitable for listening in the global scope, where the global is relative to the global, relative to a top-level node and the node of all descendants of the formation of the collection range.

For example, you want to make a global click event monitoring, relative to the document node and all the sub-nodes under the document, under a certain condition requires all sub-node click Invalid, in this case the bubble model can not be solved, but the capture type is very suitable for the top-level node to add the capture-type event listener, The pseudo code is as follows:

1 function Globalclicklistener (event) {
2 if (Caneventpass = = False) {
3//Cancel event further transfer to child nodes and bubbling Pass
4 event.stoppropagation ();
5//Cancel default execution after browser event
6 Event.preventdefault ();
7}
8}

In this way, when the caneventpass condition is false, all of the child node click Registration Events under document will not be processed by the browser.

2. Bubble-Type applications

It can be said that we usually use the bubble event model, because IE only support this model. Here again, the proper use of the model can improve scripting performance. In some frequently triggered events of the element, such as
OnMouseMove
Onmouseover,onmouseout, if there is no need for further delivery after the event is clear, then you can boldly cancel it. In addition, the handling of child node event listeners is
Layer listener processing, you should also suppress the event further upward in the child node listener to eliminate the impact.

Comprehensive case Study

Finally, we combine the following HTML code for analysis:

1 <body onclick= "alert (' Current is body ');" >
2 <div id= "Div0" onclick= "alert (' current is ' +this.id) ' >
3 <div id= "Div1" onclick= "alert (' current is ' +this.id) ' >
4 <div id= "Div2" onclick= "alert (' current is ' +this.id) ' >
5 <div id= "event_source" onclick= "alert (' current is ' +this.id)" style= "height:200px;width:200px;" ></div>
6 </div>
7 </div>
8 </div>
9 </body>
10

After the HTML run, click on the red area, which is the innermost div, according to the above, whether it is the DOM standard or IE, directly written in the HTML of the listener handler function is the event bubbling pass the call, from the innermost layer has been passed up, so will appear
Current is event_source
Current is Div2
Current is Div1
Current is Div0
Current is body

Add the following fragment:

1 var div2 = document.getElementById (' div2 ');
2 Eventutil.addhandler (Div2, ' click ', Function (event) {
3 event = Eventutil.getevent (event);
4 Eventutil.stoppropagation (event);
5}, False);

Event_sourcecurrent is Div2

When you click on the red area, according to the above description, during bubble bubbling processing, the event is passed to Div2 after it is stopped, so the elements of the upper layer div2 not receive notification, so will appear:

In a browser that supports DOM standards, add the following code:

1 Document.body.addEventListener (' click ', Function (event) {
2 event.stoppropagation ();
3}, True);

The listener function in the above code is called because it is a capture type, so after clicking on the red area, although the event source is an element with ID event_source, but captures the selection pass, starting at the topmost level, the Body node listener function is called first, and the event is canceled further down, so it only appears Current is body.

Original address: http://cssrainbow.cn/tutorials/javascript/1027.html

Rainbow

Understanding event Handling in JavaScript prevents bubbling event.stoppropagation ();

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.