JS Event stream, Event Handler/event Listener

Source: Internet
Author: User
Tags event listener

1. Event Flow

Event bubbling

The event stream of IE is called event bubbling, where the event starts with the most specific element (the node that is the deepest nesting level in the Document) and then propagates up to the less specific node (document).

Event capture

The idea of event capture is that less specific nodes should receive the event earlier, while the most specific node should receive the node at the End. Event capture is intended to capture an event before it reaches a predetermined target.

Dom Event Flow

The event flow defined by the DOM2 level event flow consists of three stages: the event capture phase, the target stage, and the bubbling Phase. The first occurrence is event capture, which provides an opportunity to intercept the Event. Then the actual target receives the Event. The final stage is the bubbling phase, in which events can be responded to at this Stage. For an example of a simple HTML page, click the <div> element to trigger the event in sequence

In the DOM event stream, the actual target (<div> Element) does not receive events during the capture Phase. This means that during the capture phase, events are stopped from document to

Most browsers that support DOM event streams implement a specific behavior, even though the DOM2 level event specification explicitly requires that the capture phase not involve the target of the event, but safari, Chrome, firefox, and Opera9.5 and later will trigger events on the event object during the capture Phase. As a result, there are two opportunities to manipulate events above the target Object.

Opera, Firefox, chrome, and Safari all support DOM event streams, and IE does not support DOM event Streams.

2. Event handlers (or event Listeners)

An event is an action that is performed by the user or the browser itself. such as click, load, and mouseover are the names of the Events. The function that responds to an event is called an event handler (or event listener). The name of the event handler begins with "on", so the event handler for the Click event is the onclick, and so On. There are several ways to specify handlers for Events.

HTML Event handlers

Each event supported by an element can be specified using an HTML attribute with the same name as the corresponding event Handler. Such as:

<input type= "button" value= "click me"  onclick= "alert (' Clicked ')"/>
<script type= "text/javascript" >    function showmessage () {        alert ("Hello world!");    } </script><input type= "button" value= "click me"  onclick= "showmessage ()"/>

There are two disadvantages to specifying an event in Html. first, There is a time difference problem. Because the user may trigger the corresponding event at the time the HTML element appears on the page, the event handler may not yet have an execution Condition. For example, assuming the ShowMessage function is defined at the bottom of the page below the button, if the user clicks the button before the page resolves the showmessage function, an error is Raised. The second certainty is that HTML is tightly coupled with JavaScript code. If you want to change the event handler, you need to change two places.

DOM0 Level Event handlers

The traditional way to specify event handlers through JavaScript is to assign a function to an event handler Property. To specify an event handler using javascript, you must first obtain a reference to the object you want to Manipulate.

Each element, including window and document, has its own event handler properties, which are usually lowercase, such as the ONCLICK. You can specify an event handler by setting the value of this property to a Function.

An event handler that is specified by using the DOM0-level method is considered a method of the element, so it is run in the scope of the element, in other words, the This in the program refers to the current Element.

var btn = document.getElementById ("mybtn"); Btn.onclick = function () {    alert (this.id);   "mybtn"};

Any properties and methods of the element that can be accessed through this in an event handler are processed in the bubbling phase of the event stream in such a way that the event handlers are Added.

You can delete an event handler that is specified by the DOM0-level method, as long as the value of the event handler property is set to Null.

Btn.onclick = null;  To delete an event handler

DOM2 Level Event handlers

The "DOM2 level event" defines two methods for handling the actions of the specified and deleted event handlers: AddEventListener () and RemoveEventListener (). Both methods are included in all Dom nodes, and they all accept three parameters: the name of the event to be processed, the function that is the event handler, and a Boolean Value. The last Boolean value, if true, indicates that the event handler is called during the capture phase and, if false, that the event handler is called during the bubbling phase .

Like the DOM0-level approach, the event handlers for the DOM2-level method Horizon are also in the scope of the elements to which they are attached. The main benefit of adding event handlers using the DOM2-level method is that you can add multiple event Handlers. Take a look at the following example:

Btn.addeventlistener ("click", function () {    alert (this.id);},false); btn.addeventlistener ("click", function () {    Alert ("Hello world!");},false);

There are two additional event handlers added to the Button. The two event handlers are triggered in the order in which they were added, so the element ID is displayed first, followed by the "Hello world!" News.

Event handlers added through AddEventListener () can only be removed by using removeeventlistener, and the parameters passed in when they are removed are the same as those used when adding handlers. This also means that anonymous functions added via AddEventListener () will not be removed, as Follows:

var btn = document.getElementById ("mybtn"), btn.addeventlistener ("click", function () {    alert (this.id);},false); Btn.removeeventlistener ("click", function () {  //no use!)    Alert (this.id);},false);
var btn = document.getElementById ("mybtn"), var handler = function () {    alert (this.id);}; Btn.addeventlistener ("click", handler,false); btn.removeeventlistener ("click", handler,false);  Effective!

In most cases, the event handlers are added to the bubbling phase of the event stream, which allows for maximum compatibility with various Browsers. It is best to add an event handler to the capture phase only when it is needed to intercept the event before it reaches its destination. If not specifically required, we do not recommend registering an event handler during the event capture Phase.

Firefox, Safari, chrome, and opera support DOM2-level event handlers

IE Event handlers

IE implements two methods similar to dom: attachevent () and DetachEvent (). Both methods accept the same two parameters: the event handler name and the event handler Function. Because IE only supports event bubbling, event handlers added through Attachevent () are added to the bubbling Phase.

var btn = document.getElementById ("mybtn"), btn.attachevent ("onclick", function () {    alert ("Clicked");});

Note: The first parameter is "onclick", not the "click" in the Dom's addeventlistener () method.

The main difference between using attachevent () in IE and using DOM0-level methods is the scope of the event Handlers. The DOM0-level event handler runs within the scope of the element to which it belongs, and in the case of the attachevent () method, the event handler runs in the global scope, so this is equal to WINDOW. It is important to keep this distinction in mind when writing Cross-browser Code.

Attachevent () can also add multiple event handlers for an element, and take a look at the following example:

var btn = document.getElementById ("mybtn"), btn.attachevent ("onclick", function () {    alert ("Clicked");}); Btn.attachevent ("onclick", function () {    alert ("Hello world!");});

Unlike Dom methods, these event handlers are not executed in the order in which they were added, but are triggered in reverse order . Click the button in this example to see "Hello world!" first, then "Clicked".

Events added using attachevent () can be removed by detachevent (), provided that the same parameters must be Supplied. As with Dom methods, the added anonymous function cannot be Removed.

var btn = document.getElementById ("mybtn"); var handler = function () {    

JS Event stream, Event Handler/event Listener

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.