JavaScript event model and event broker

Source: Internet
Author: User
Tags event listener

Event model

JavaScript events make Web pages interactive and interactive, and we should understand them in order to develop work, in a variety of browsers, JavaScript event model is divided into 3 kinds: Original event model, DOM2 event model, IE event model.

1. Original event model (DOM0 level)

This is an event model that is supported by all browsers , there is no event flow for the original event, the event will be processed immediately once it occurs, there are two ways to implement the original event:

(1) Specify the attribute value directly in the HTML code: <button id= "Demo" type= "button" onclick= "dosometing ()"/>

(2) in the JS code for Document.getelementsbyid ("demo"). OnClick = Dosometing ()

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

Because of these drawbacks, although the original event type is compatible with all browsers, it is still not recommended.

2.dom2 Event Model

This model is a standard model developed by the web, and modern browsers (except Ie6~8) have followed this specification. In the event model developed by the consortium, the occurrence of an event consists of three processes:

(1). Event Capture phase, (2). Event Target stage, (3). event bubbling phase. As shown

Event capture: When an element triggers an event (such as an onclick), the top-level object document emits an event stream as the DOM tree's node flows to the target element node until it reaches the target element that the event actually occurs. In this process, the corresponding listener function of the event is not triggered.

Event target: When the target element is reached, the corresponding handler function is executed for the event of the target element. If the listener function is not bound, it is not executed.

Event bubbling: Starts at the target element and propagates toward the top level element. On the way, if a node is bound to a corresponding event handler, these functions are triggered at once.

All event types experience event capture, but only some events go through the event bubbling phase, such as the Submit event, which is not bubbling.

The propagation of events can be prevented:
• Use the Stoppropagation () method in the
• Set cancelbubble = True under IE;
Stoppropagation () in the process of capture, the subsequent bubbling process will not occur.

  How the standard event listener is bound:

AddEventListener ("EventType", "handler", "True|false"), where EventType refers to the event type, be careful not to add the ' on ' prefix, unlike IE . The second parameter is the handler function, and the third is used to specify whether to process in the capture phase, which is generally set to false to be consistent with IE (the default) unless you have special logic requirements. The listener's release also resembles: Removeeventlistner ("EventType", "handler", "True!false");

3.IE Event Model

  IE does not pass the object to the event handler, because at any time there will only be an event, so IE takes it as a property of the Global Object window , in order to verify its authenticity, using IE8 Code alert (window.event), the result popup is null , which indicates that the property is already defined, except that the value is null (unlike undefined). Is the property of this global object 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. Bubbling has been explained, and there is no repetition here. 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.

The above is 3 kinds of event model, when we write code, in order to be compatible with IE, usually use the following wording:

var demo = document.getElementById (' demo ');

if (demo.attachevent) {

Demo.attachevent (' onclick ', func);

}else{

    Demo.addeventlistener (' click ', Func,false);

    }

Event explanation

The above has explained 3 kinds of event models, events, in most cases refers to the user's mouse action and keyboard action, such as click, move the mouse, press a key, why say most of it, because the event is not only these two parts, there are other such as document load and unloaded. So what information does the event contain in the browser?

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

  I bound a click event for the button in, and then output the event to the console:

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, the property is not the same as the above, such as no clientx/y (tapping the keyboard how to get to the position of the mouse). Whether it is mouseevent or keyboardevent or any other type, it is inherited from a class called event.

Event object Common Properties, methods: 1. Event Location related properties

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/offsety six pairs. Why are there so many X-y? Do not worry, as a web developer, you should understand that there are differences between the browsers, these attributes have their own meaning:

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 browser support for each property is listed below. (+ support,-not supported)

w3c-  ie+  F irefox- /tbody>
offsetx/offsety w3c-  ie+  firefox- opera+  safari+ chrome+
x/y opera+  safari+ chrome+
layerx/layery -  ie-  firefox+ opera-  safari+ chrome+
pagex/pagey w3c-  ie+- firefox+ opera+  Safa ri+ chrome+
clientx/clienty w3c+  ie+  firef ox+ opera+  safari+ chrome+
screenx/screeny w3c+< /td>  ie+  firefox+ opera+  safari+ chrome+

Note: This table is excerpted from other articles, I did not do all the validation, but the latest version of the modern browser, these properties seem to be supported, for better compatibility, usually choose the properties supported by the world.

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 prevent the same event of other low-priority listener processing (this goods said no use, priority does not explain, Google or ask Niang bar.) )

What's the difference between Event.target and event.currenttarget?

Target in the phase of the event flow, the capture, the target, and the bubbling phase of the currenttarget. The two points are the same only when the event flow is at the target stage, and when in the capture and bubbling phase, target points to the object being clicked and Currenttarget to the object that is the current event activity (usually the parent).

  

event triggers

  The previously mentioned events are triggered by the user or browser to bring the event, such as click is the user click the event target trigger, load is the specified element is loaded when the browser's behavior event, and so on, if only under these conditions can trigger the event, then how our custom event trigger?

JavaScript event model and event broker

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.