javascript--Event Model

Source: Internet
Author: User
Tags event listener

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).

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.

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.

javascript--Event Model

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.