JavaScript Event Model Series (i) Three models of events and events

Source: Internet
Author: User
Tags event listener

Reprint: http://www.cnblogs.com/lvdabao/p/3265870.html

First, the outset

In the beginning of the study of JavaScript, on the Internet to read a lot of articles on the introduction of JavaScript, after all, is the basis of JS Foundation, the article fragmented there are many, but unfortunately did not see a more comprehensive series of articles. Still remember this time last year, participated in the interview of the intern of Baidu, was asked the incident model, at that time was asked confused, usually knocks the onclick to knock quite cool, but did not pay attention to the whole concept of the event model. This weekend is rarely idle, decided to write a series of JavaScript event model, a summary of knowledge points, but also an account of their own.

The preliminary plan is divided into the following sections:

The basic concept of ①javascript event and the similarities and differences of three models based on primitive, IE and DOM2

②javascript Event Flow Introduction, capture-bubbling mechanism and event delegation mechanism

Event monitoring methods in ③jquery (Bind, Live, attachevent, on) and similarities and differences

④javascript Custom Events

Ii. Introduction of the event

What is an event? Intuitively speaking is what happens on the webpage, most of it refers to the user's mouse action and keyboard action, such as click, move the mouse, press a key. Why most of it, because the event is not just these two parts, there are other such as document load and unloaded. But we are more concerned about the user's operation. Events are encapsulated into an event object that contains all the relevant information (the properties of the event) and the actions that can be taken on the event (the method of the events).

Event long what kind of, to intuitively look at, for example, I click on the page of the previous button, the resulting event object is as follows:

Can see is a MouseEvent object, contains a series of properties, such as the location of the mouse click. Does the event object that is created when you tap the keyboard are the same as it does? Just look at it and know:

Can see is a KeyboardEvent object, and the property is not the same as the above, such as no clientx/y, it is taken for granted, how to hit the keyboard to get to the mouse position it.

If you have a bit of object-oriented programming basis, see these two class names should be thinking, MouseEvent, KeyboardEvent will be inherited from a class called event? Congratulations, you guessed it, that's true. To take a look, I print the event object in the Window.onload listener function as follows:

property is a lot less, after all, is the parent class. If you want to learn more about the event type, you can refer to this article for more details.

Third, the event object commonly used properties, Method 1. Event Location related properties

This part of the properties usually use a lot of, so we have to focus on the introduction. If you look at the properties in the MouseEvent object, you must have found a lot of properties with X/Y, which are related to the location of the event. Specific include: X/y, Clientx/clienty, Pagex/pagey, Screenx/screeny, Layerx/layery, offsetx/offset six pairs. A bit messy, how many locations can a click event be? Do not worry, in fact, not complex, the reason why there are so many are because the browser vendors in the version of the change in the time produced a lot of inconsistencies. See the following example to understand the meaning of each:

Move the mouse here x: y:
ClientX: ClientY:
ScreenX: ScreenY:
OffsetX: OffsetY:
PageX: Pagey:
Layerx: Layery:

The following conclusions are drawn:

X/y is the same as the Clientx/clienty value, representing the distance from the left/top of the viewable area of the browser (except the toolbar);

Pagex/pagey, the distance from the left/top of the page, the difference between it and the Clientx/clienty is not changed with the position of the scroll bar;

Screenx/screeny, the distance from the computer monitor left/on, drag your browser window position can see changes;

Layerx/layery, like the Offsetx/offsety value, represents the distance from the left/top of the parent element with a positional property.

The reason why so many values are the same is due to browser compatibility. So how do we usually use it? See the table below for browser support for each property. (+ support,-not supported)

offsetx/offsety:w3c-ie+ firefox-opera+ safari+ chrome+

x/y:w3c-ie+ firefox-opera+ safari+ chrome+

layerx/layery:w3c-ie-firefox+ opera-safari+ chrome+

pagex/pagey:w3c-ie-firefox+ opera+ safari+ chrome+

clientx/clienty:w3c+ ie+ firefox+ opera+ safari+ chrome+

screenx/screeny:w3c+ ie+ firefox+ opera+ safari+ chrome+?

Description: The table was taken from other articles, I did not do all the validation, but from the latest version of modern browsers, these properties seem to be supported, for better compatibility, we usually choose to support the world. If you would like to see a more detailed description, please click here.

2. Other Common Properties

Target: The node where the event occurred;

Currenttarget: The node of the event currently being processed, in the event capture or bubbling phase;

TimeStamp: The time, time stamp, at which the event occurred.

Bubbles: Whether the event is bubbling.

Cancelable: Whether the event can use the Preventdefault () method to cancel the default action;

KeyCode: The value of the key pressed;

3. Method of the Event object

Event. Preventdefault ()//block The default behavior of the element, such as linked jump, form submission;

Event. Stoppropagation ()//block event bubbling

Event.initevent ()//Initialize the properties of the new event object, custom events will be used, not commonly used

Event. Stopimmediatepropagation ()//can block the processing of other low-priority listeners of the same event (I have not used it)

Iv. Three models of events

Due to complex historical reasons, the event model is not uniform, of course, as a front-end developers This kind of thing has been more than flattering. Although the DOM2 standard has been established to standardize the definition of events, but because of the stubborn IE6, 7, 8 exist, we still have to understand the definition of IE. So let's see what all three models have.

1. Original Event model

In the original event model (and also the DOM0 level), there was no concept of propagation after the event occurred, no event flow. It happens, it's done right away, it's so simple. A listener function is simply a property value of an element that binds the listener by specifying the attribute value of the element. There are two ways of writing:

Specify attribute values in ①html code: <input type= "button" onclick= "func1 ()"/>

② Specify the attribute value in the JS code: document.getElementsByTagName (' input ') [0].onclick = Func1

Pros: All browsers are compatible

Cons: 1) The logic and the display are not separated; 2) the listener function of the same event can only bind one, and then the binding will overwrite the previous, such as: A.onclick = func1; A.onclick = Func2; only the content in FUNC2 will be executed. 3) It is not possible to do more with events bubbling, delegating, and so on (later in the series).

In the current Web application modularization development and more complex logic situation, this way is obviously outdated, so in the real project is not recommended to use, usually write a little blog Small example of what is can, faster.

2. IE Event model

In reference to other materials, I have seen such a sentence "IE does not pass the object into the event handler, because at any time there will only be an event, so IE takes it as a global object window of a property", in order to verify its authenticity, I used IE8 code alert ( window.event), the result popup is NULL, indicating that the property is already defined, except that the value is null (unlike undefined). I wonder if the properties of this global object are added in the listener function? Then execute the following code:

Window.onload = function () {alert (window.event);}

SetTimeout (function () {alert (window.event);},2000);

The result pops up "object event" for the first time, and the popup remains null after two seconds. This shows that IE is a property that sets the event object to window in the handler function, and once the function execution is finished, it is set to null. IE's event model has two steps, first executing the element's listener function, then the event bubbles up to the document along the parent node. The bubble mechanism behind the series will say, here suspense. The mode of event listening under IE model is also very unique, the method of binding listener function is: attachevent ("EventType", "handler"), where Evettype is the type of event, such as onclick, note to add ' on '. The method to dismiss the event listener is detachevent ("EventType", "handler")

IE's event model has been able to solve the original model of the three shortcomings, but its own shortcomings is compatibility, only IE series browser can write this.

3. DOM2 Event Model

This model is the standard model of the web, since it is the standard, everyone must press this, we are now using the modern browser (referring to ie6~8 except for the browser) has been following this specification. In the event model developed by the consortium, the occurrence of an event consists of three processes:

(1) Capturing phase: Event capture phase. The event is propagated from document down to the target element, which in turn checks to see if the passed node registers the listener function for the event, and executes if any.

(2) Target phase: Event processing phase. The event arrives at the target element and executes the event handler for the target element.

(3) Bubbling phase: event bubbling phase. The event rises from the target element until the document is reached, and in turn checks whether the passed node registers the listener function for the event, and then executes.

All event types go through captruing phase but only part of the event goes through the bubbling phase phase, such as the submit event that is not bubbling.

You may have questions, why is it like this? There's a lot of process, right? The cause of the matter has to start with Netscape and Microsoft hegemony. In the specification has not yet been born, the market has two strong browser vendors, the products are Microsoft's IE and Netscape Netspace Navigator (hereafter referred to as NN), IE's event model has been described above, events can be bubbling. However, NN does not think so, its model, the event is from the top down, that is, only the capture phase. Neither of the two families is right or wrong, because the event can be handled according to their model. Then the long overdue late, to set standards, to unify, so it can only be adopted by two, who can not sin, and then use the tone of the standard-makers announced: the model works well. This is the most peaceful.

Say it far, hurry and see how the standard event listener binds: AddEventListener ("EventType", "handler", "True|false"), where EventType refers to the type of event, take care not to add ' On ' prefix, different from IE under. The second parameter is the handler function, and the third is used to specify whether to process in the capture phase, generally set to false to be consistent with IE, unless you have special logic requirements. The listener's release also resembles: Removeeventlistner ("EventType", "handler", "True!false");

The above is the three models of the event, we need to take into account the development of IE and non-IE browser, so register a listener should write:

var a = document.getElementById (' A 'if(a.attachevent) {     a.attachevent (' OnClick 'else{     a.addeventlistener (' click ', Func,false);}

Feeling a lot of trouble, huh? As a result, we tend to use existing frameworks or class libraries that are already encapsulated, such as jquery, which will introduce the powerful event-monitoring approach in jquery.

Series one to this end, the author's own technical level is limited, the article is their own understanding of the written, welcome to the road Master guidance error correction.

JavaScript Event Model Series (i) Three models of events and events

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.