Explore five types of event handlers in JavaScript _javascript tips

Source: Internet
Author: User
Tags anonymous event listener function definition script tag

We know that the interaction between JavaScript and HTML is done through events.  Events were first seen in IE3 and Netscape Navigator 2, as a means of sharing server computing load. In layman's sense, an event is an operation performed by a user or a browser itself. An event handler is a function that responds to an event.  Extracts the backbone, which is the event handler as a function.  We also refer to the event handler as an event listener. The event handler starts with "on", so the time handler for the event on is onclick. There are roughly five types of time handlers in JavaScript, which are described in 5 parts based on these five different time handlers.

1.HTML Event handlers

2.dom0-level event handlers

3.dom2-level event handlers

4.IE Event handlers

5. Cross-browser event handlers

First part: HTML event handlers

What makes an HTML event handler? Obviously, by name, it's a function in the Unload HTML (event handler). The most commonly used event handlers for beginners are HTML event handlers. Here are some examples:

Example 1:

<button onclick= "alert (' Success ')" > Dot i </button>

This code is the event handler, click the button, pop-up frame, show success.

Features: The JavaScript code in the HTML event handler is the value of the onclick attribute, so we can't use the unused HTML syntax characters in JavaScript code, such as & (and number), "" (double quotes), < (less than), > (Greater-than number), and so on. So in this example, I use single quotes instead of double quotes in the string. Look at the following use of the HTML syntax characters that are not escaped in JavaScript code.

Example 2:

<button onclick= "alert (" Success ")" > Dot i </button>

At this time, I used the HTML syntax character "" (double quotation mark) outside the success, this time does not pop the window, but the error errors syntax. But what if I still want to use double quotes? Instead, use the entity to replace the syntax characters in HTML. As shown in the following example:

Example 3:

<button onclick= "alert (" Success ")" > Dot i </button>
  <!--normal pop-up window-->

In this example we use HTML entities in JavaScript code without using HTML syntax characters, and there is no error.

Example 4:

<button onclick= "Show ()" > Dot i </button>

<!--normal pop-up window--> 

<script>

  function Show () {

    alert ("Success");

  }

</script> 

In this example we call the function and put the function definition in the script, which is OK. Because: the code in the event handler has permission to access any code in the global scope at execution time.  How do you understand this sentence? In fact, we can look at the button tag's scope chain in Chrome. As shown below:

Next we look at the scope of the script, as shown in the following illustration:

You can see that the script tag is in the global scope.

That is, the HTML event handler function in the current button is at the very front of the scope chain, and the script is in the global scope, so "code in the event handler has access to any code in the global scope at execution time." "It is not difficult to understand this sentence."

Example 5:

<button onclick= "alert (event.type)" > Dot i </button>

The Browser pop-up window displays: click. What does this example mean? Notice that I'm not event.type with single quotes to show that this is not a string. In fact, the event is a local object-when an event is triggered on the DOM, an event object is generated that contains all the information related to the event. And here is the type of object that pops up, that is click.

Three disadvantages of HTML event handlers (emphasis):

1. Jet lag problem. Because the user may start triggering the corresponding event as soon as the HTML element appears, it is possible that the script for the event (in Example 4, the function definition of the show () function in script) has not been loaded yet, and there is no execution condition at this time, so the error occurs.

WORKAROUND: Encapsulate the HTML event handler in a Try-catch block so that the error does not surface.

<input type= "button" value= "click Me" onclick= "try{show ();} catch (ex) {} ">

2. The scope chain of the extended event instance program can result in different results in different browsers (example 4 I am viewing the scope chain in Chrome, other browsers may not be, please note). Different JavaScript engines follow a slightly different identifier resolution rule and are likely to have an error accessing unqualified object members.

3.HTML is tightly coupled with JavaScript code. The result: If you want to replace the event handler, you must change two local--html code and JavaScript code.

So how to solve the above problem? DOM0-level event handlers are a good choice!

Part II: DOM0 Level Event handlers

DOM0-level event handlers are also very common. As a DOM0 level, I think there was no DOM standard at the time, and IE and Netscape Navigator both use of the time processing program (I do not know whether reasonable, I hope to criticize). Anyway, let's take a look at the example below.

Example 6:

<button id= "button" > Dot i </button>

<script>
  var button=document.getelementbyid ("button");
  Button.onclick=function () {
    alert ("clicked");
  }
</script>

That is, we first take a reference to the element in the script, and then assign a function to the OnClick event handler. As described earlier, the event handler is a function, and button.onclick This form is the method of a function as an object. The object's method is that the event handler runs in the scope of the element (object) rather than in the global scope, because the method belongs to the object. (Note: in Example 4, an event handler is run in a global scope). If this keyword exists in this function, then this will point to this object. Here we prove in the browser that the event handler is running in the scope of the element.

We see alert ("clicked"); it's actually running in a button.

We can also delete the event handlers specified by the DOM0 level method in the following way.

Button.onclick=null;

Through the above analysis, we can know that the DOM0 level event handler is very good, it solves the HTML event handler three disadvantages: The time difference problem, the scope chain causes the different browser performance inconsistency problem and the HTML and JavaScript tightly coupling problem.

However, the DOM0-level event handler is not perfect, and it has two drawbacks:

1. We cannot add two events to an element at the same time.

2. We cannot control the event flow (capturing or bubbling) of the element.

For the second question, the first one, for example, is as follows:

<button id= "button" > Dot i </button>

<script>
  var button=document.getelementbyid ("button");
  Button.onclick=function () {
    alert ("clicked");
  }
  Button.onclick=function () {
    alert ("Again");
  }

Although I set up two event handlers for the same element, the end result is that only the second event is valid (overwriting the first event). Of course, human beings are intelligent animals, the DOM2-level event is a good solution to this problem!

Part III: DOM2 level Event handlers

The DOM2 level event handler defines two methods:

    • AddEventListener ()---Add event listeners
    • RemoveEventListener ()---Delete event listeners

I mentioned the event handler, the event listener, at the beginning of the blog post. Both of these methods receive three parameters:

1. Event name to process (note: Is the time name, so there is no on! ), such as Click, MouseOver and so on.

2. Functions as event handlers, such as function () {alert ("clicked");}

3. Boolean value representing the way the event flows. False for the bubbling phase invoke event handler; True to invoke the event handler for the capture phase.

Below are two examples to deepen the understanding:

Example 7:

<button id= "button" > Dot i </button>

<script>
  var button=document.getelementbyid ("button");
  Button.addeventlistener ("click", Function () {
    alert (this.id);
  },false);
  Button.addeventlistener ("click", Function () {
    alert ("another event");
  },false);
</script>

Results: First pop-up window: button.

Second pop-up window: another event.

Conclusion: Through the DOM2 level event handler, we can add two or more events to the same element. Events are triggered sequentially, in sequence. And this also points to the current element, so the function executes in the scope of the element.

This analysis: Like the previous DOM0 level event handler, the AddEventListener can also be viewed as an object method, at the beginning of which the DOM0-level method requires another function to assign the value, and the method here is predefined by the DOM2-level specification.

RemoveEventListener () This method of deleting an event handler is noteworthy: an event handler added using AddEventListener () can only be removed through it, and the same parameters need to be passed in.

Example 8:

<button id= "button" > Dot i </button>

<script>
  var button=document.getelementbyid ("button");
  Button.addeventlistener ("click", Function () {
    alert (this.id);
  },false);
  Button.removeeventlistener ("click", Function () {
    alert ("another event");
  },false);

The above code seems to remove the Click event handler, but it is not possible to do so experimentally, because an event handler cannot be removed when it is an anonymous function. See the following example of successful removal:

Example 9:

<button id= "button" > Dot i </button>

<script>
  var button=document.getelementbyid ("button" );
  function handler () {
    alert (this.id);
  }
  Button.addeventlistener ("click", Handler,false);
  Button.removeeventlistener ("click", Handler,false);
</script>

Successfully removed!

Note: 1. The handler of the incoming method is not (), because this is all just a function, not a call, to be noted.

2. The third parameter of both methods is false, that is, the event handler is added to the bubbling phase. Generally, true is not used because the lower version of IE does not support the capture phase.

The DOM2 level event handler successfully resolves all of the previous event handlers and is called perfect!!!! However, always maverick IE browser has a twist, it also has its own set of event handlers, let's take a look at the following.

Part IV: IE event handlers

The IE event handler has two methods similar to the DOM2 level event handler:

1.attachEvent ()

2.detachEvent ()

They all receive two parameters:

1. event handler name. such as onclick, onmouseover, note: This is not an event, but the name of an event handler, so there is on.

2. event handler function. such as function () {alert (' clicked ');}

The third parameter that is similar to the DOM2 level event handler is not available because IE8 and earlier versions only support bubbling event flow.

Attention:

The scope and DOM0 of the event handlers for Attachevent () in the 1.IE event handler are different from the DOM2, and her scope is in the global scope. Therefore, unlike DOM0 and DOM2, this points to the element, this in IE points to window.

2. Similarly, we can use Attachevent () to add multiple event handlers to the same element. However, unlike DOM2, the sequence of events is not the order in which they are added, but rather the order in which they are added.

3. Similarly, event handlers added through Attachevent () must be removed through the DetachEvent () method, and, similarly, anonymous functions cannot be used.

4. Browsers that support IE event handlers are not only IE browsers, but also opera browsers.

Part V: cross-browser event handlers

In fact, this part is considered to be used across browsers, and the previous few points can be combined.

This section requires the creation of two methods:

    • AddHandler ()-This method is responsible for adding events using the DOM0 level, DOM2 level, IE event handlers as appropriate.
    • RemoveHandler ()-This approach is to remove events that were added using AddHandler.

The two methods receive the same three parameters:

1. Elements to be manipulated--fetching by Dom method

2. Event name-note: No on, such as Click, MouseOver
3. event handler function--that is, the handler function

The two methods are constructed as follows:

var eventutil={
  addhandler:function (element,type,handler) {
    if (element.addeventlistener) {
      Element.addeventlistener (Type,handler,false)//NOTE: The default is to use False (bubbling)
    }else if (element.attachevent) {
      Element.attachevent ("on" +type,handler);
    else{
      element["on" +type]=handler
    }
  },
  removehandler:function (element,type,handler) {
    if ( Element.removeeventlistener) {
      element.removeeventlistener (type,handler,false);//NOTE: This defaults to using false (bubbling
    ) }else if (element.detachevent) {
      element.detachevent ("on" +type,handler);
    } else{
      element["on" +type]=null;
    }
  }
;

That is, judge the DOM2 level event handler first, then Judge IE event handler, and finally use DOM0 level event handler.

Example 10: Using this example to use the method constructed above.

<! DOCTYPE html>  

Finally, the browser successfully pops up "clicked".

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.