JavaScript Event handling

Source: Internet
Author: User
Tags ocaml

"Write in front" recently has been looking at the basis of JS, after all, although jquery is easy to use, it is always written by others, will only use the API to understand the principle of implementation. And so the JS Foundation to consolidate well must read the source of jquery.

Event Flow

The event flow describes the order in which events are received from the page. JS has two kinds of event streams, bubbling streams and capturing streams. The names of both streams are very vivid, and on top of an HTML tree made up of nodes, the bubbling stream refers to the first time that the event starts with the most specific element, and then propagates to the least specific node, such as in the following document:

<!doctype html><html><head></head><body>    <div></div></body></html>

When you click a div, the event first responds to the Div, then to the BODY element, then to the HTML element, and finally to the document object.
Capturing the stream is the opposite, the first response is the document object, and then along the DOM tree down, to the HTML, to the body, and finally to the actual target, that is, the Div.
Older browsers do not support capturing streams, and bubbling streams are very much in line with our understanding of event propagation, so we are using bubbling streams more.

Several methods of event handling

There are many kinds of events defined in the event processing of JS, the event name refers to a specific action, such as click, Load, mouseover, etc. are the name of the event. The function that responds to an event is called an event handler, and the name of the event handler begins with on, so the event handler for the Click event is the event handler for the Onclick,load event, which is onload.

Binding within tags

By setting the properties of a label, you can easily bind an event to a node, such as:

type="button"value="按钮" onclick="alert(‘按钮按下‘)">

You can also invoke scripts that are defined elsewhere:

<script>    function showMessage(){        alert("按钮按下");    }</script>...<input type="button" value="按钮" onclick="showMessage()">

There are two special places to use direct binding, one is to create a function that encapsulates the attributes of the element , which has a local variable event, the event object:

<!--输出‘click‘--><input type="button" value="按钮" onclick="showMessage(event.type)">

When an event is generated, the event object is automatically passed to the ShowMessage function, through which we can access many of the properties of the event object. Also inside the event handler, this refers to the target element of the event, such as

<!--输出‘按钮‘--><input type="button" value="按钮" onclick="showMessage(this.value)">

In addition, when the current element is a form element, the scope also contains the entry for the form element , which means that other form elements can be accessed in the event handler, such as

<form>    type="text" name="username"/>     type="button"value="按钮" onclick="alert(username.value)"></form>

This allows you to directly output the values in the username.

However, the handling of events added in this way is intuitive and convenient, but there are a number of drawbacks:
(1) Because the page load order is from the top down, if the binding script is written under the HTML, the user may click on the element when the script has not been executed, causing the user point half a day did not respond, such as:

<input type="button" value="按钮" onclick="showMessage()">......//很多内容...<script>    function showMessage(){        //...    }</script>

(2) HTML and JS code tightly combined, such as showmessage this method, if many elements of the interface in this way to bind this method, then if a moment want to give this function to change a name, you need to change many places at the same time, rather troublesome.

DOM0 class Handler

The second way is to bind an event to an element in JS, get the element in JS, and then assign an event to it:

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

The program specified by the DOM0-level method is considered a method of the element, so after the above code executes, pressing the element pops up will be the button's ID, which can be used to get all the properties and methods of the element.
You need to delete the event handlers specified by the DOM0-level method, just set the property value to null:

btn.onclick = null;

It is important to note that you cannot add duplicate events to an element in this way, and that only the last one is valid for the onclick multiple times, such as

function(){    alert("first"function(){    alert("second");}

When you finally click the button, only the second is output.

DOM2 class Handler

IE9, Firefox, Chrome, Safari and Opera support DOM2-level event handlers
The "DOM2 level event" defines two methods that specify and delete the action of the event handler: AddEventListener () and RemoveEventListener (). All DOM nodes have this method and receive 3 parameters: event name, event handler function, and a Boolean value. This Boolean value represents whether to use capture or bubbling, true to represent processing in the capture phase, false to represent processing in the bubbling phase, and false to not fill the default.

var btn = document.getElementById("button");btn.addEventListener("click"function(){    //...}, false);

Unlike DOM0-level event handling, event handling that is bound by this method can be added multiple times, such as

var btn = document.getElementById("button");btn.addEventListener("click"function(){    alert("first"false);btn.addEventListener("click"function(){    alert(thisfalse);

And within the function This also refers to the target element, click on the button will be output first, and then output the ID of the BTN.
Events added through AddEventListener can only be removed by RemoveEventListener, and the parameters must be the same (three parameters are identical), which means that events that use anonymous function bindings cannot be removed, and it is a good idea to define the event handlers separately.

btn.addEventListener("click"function(){    alert("first"false);btn.removeEventListener("click"function(){    alert("first"false//没有效果btn.addEventListener("click"false);btn.removeEventListener("click"false//移除成功
IE Event handlers

The two methods that are similar to DOM2 level event handling are implemented separately in IE: Attachevent and detachevent (). Both of these methods receive two parameters: the event handler name and the event handler function. Because IE8 and earlier versions only support event bubbling, event handlers added in this way are added during the event bubbling phase.

var btn = document.getElementById("button");btn.attachEvent("onclick"function(){//注意是onclick    alert("first");});

There are two differences between IE event processing and other methods, first, IE's event handlers will run in the global environment.
This means that the use of this will equal window.

var btn = document.getElementById("button");btn.attachEvent("onclick"function(){    alert(this === window);  //true});

second, the event handlers added more than once are executed in the reverse order of the additions, such as

var btn = document.getElementById("button");btn.attachEvent("onclick"function(){    alert("first");});btn.attachEvent("onclick"function(){    alert("second");});

When the button is pressed, the second is output before the first is output.
To remove an event similar to the DOM2 level, call detachevent and pass it as the same argument.

Writing cross-browser event handlers

The above mentioned that there are some differences between IE and other browsers in handling events, you can write a Eventutil object to encapsulate the addition and removal events.
The implementation is to determine whether to support DOM2-level processing, if not supported by the IE method, if not support the final adoption of the DOM0-level method.

var eventutil = {//Add EventAddHandler:function(Element, type, handler) {        if(Element.addeventlistener) {//Support DOM2 levelElement.addeventlistener ( type, element, handler);}Else if(element.attachevent) {//ie Event Handling, note the on prefixElement.attachevent ("on"+ type, handler);}Else{//dom0 classelement["on"+ type] =Handler }    },//Removal eventsRemoveHandler:function(){if(Element.removeeventlistener) {//Support DOM2 levelElement.removeeventlistener ( type, element, handler);}Else if(element.detachevent) {//ie Event Handling, note the on prefixElement.detachevent ("on"+ type, handler);}Else{//dom0 classelement["on"+ type] = NULL; }    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaScript Event handling

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.