Native JavaScript Event details

Source: Internet
Author: User

jquery This write less does more framework, with more than will inevitably to the native JS above his business.

Side dishes actually do not want to write this blog, seemingly very elementary appearance, but see the network even the native JS event binding and lifting are said not understand, or decided to science.

First of all, the dishes understand is not a lot, just put my ideas and share with you.

DOM0 Event Model

The event model is evolving, and the early event model is called the DOM0 level.

DOM0 event model, supported by all browsers.

Registering the event name directly on the DOM object is the DOM0 notation, such as:

1 function (e) {};

It means registering an onclick event. Of course, it and this writing is a meaning:

1 function (e) {};

This is nothing, just two ways to access the properties of the JS object, [] The form is mainly to solve the property name is not a valid identifier, such as: object.123 positive error, but object["123"] to avoid this problem, at the same time, [] The writing, also JS wrote live, You can dynamically bind an event at run time by representing the property name with a string.

When the event is triggered, a parameter e is passed by default, indicating the event object, through E, we can get a lot of useful information, such as the coordinates of the click, the DOM element that triggered the event, and so on.

DOM0-based events, for the same DOM node, can only register one, and the same event that is registered behind it overwrites the previously registered. For example:

1 var btn = document.getElementById ("test"); 2 3 function (e) {4   alert ("OK"); 5 }; 6 7 function (e) {8   alert ("Ok1"); 9 };

The result is output ok1.

Then say this again. When an event is triggered, this refers to which DOM object the event is triggered on. For example:

1 var btn = document.getElementById ("test"); 2 3 function (e) {4   alert (this. id); 5 };

The result is output test. Because the event is registered on the DOM node with the ID test, this, of course, represents the DOM node, which is understood to be called by the DOM node when the event is triggered.

So, to dismiss the event is quite simple, just need to register the event again, set the value to NULL, for example:

1 var btn = document.getElementById ("test"); 2 3 function (e) {4   alert ("OK"); 5 }; 6 7 null;

The principle is that the last registered event is overwritten before the last registered event is set to NULL, and the event binding is dismissed.

It's not over yet, the DOM0 event model also involves events written directly in HTML. For example:

1 <  ID= "Test"  class= "Test"  onclick= "exec ();" ></ Div >

Events registered in this manner also follow the overriding principle, which can only be registered one and the last one to take effect.

The difference is that registering an event like this is a dynamic call to a function (a bit of eval), so the event object is not passed in, and this is the window that is no longer the DOM object that triggered the event.

DOM2 Event Model

DOM2 event model compared to DOM0, the side dishes only know the following two points:

· DOM2 supports the same DOM element to register multiple same-event events.

· DOM2 added the concept of capture and bubbling.

DOM2 events are managed through AddEventListener and RemoveEventListener, of course, which is standard.

But IE8 and the following version of the browser, amuse themselves, made the corresponding attachevent and detachevent, because of the side dishes Caishuxueqian, this article does not discuss.

AddEventListener Of course is the registration event, she has three parameters, respectively: "Event name", "Event callback", "Capture/bubble". As an example:

1 var btn = document.getElementById ("test"); 2 3 function (e) {4   alert ("OK"); 5 false);

The event name does not have to say more, compared to DOM0, removed the front of the on just.

The event callback is also well understood, the event triggered the must inform you! Callbacks, like DOM0, pass in an event parameter by default, and this is the DOM node that triggers the event.

The last parameter is a Boolean, and true represents the capture event, and false represents the bubbling event. In fact, very good understanding, first of all:

This means that an element triggers an event, the first to be notified is the window, then the document, and in turn, until the element that really triggers the event (the target element), the process is captured. Next, the event bubbles from the target element, and then sequentially out until the Window object, the process is bubbling.

Why design it like this? This seems to be due to the deep historical origins, the side dish also does not understand, will not utter nonsense.

As you can see, the capture event is triggered before the bubbling event.

Suppose you have such an HTML structure:

 1  <  div  id  = "Test"   class  = "Test"  >  2   id  = "Testinner"   class  = "Test-inner"  ></ Span style= "color: #800000;" >div  >  3  </ div  >  

We then register two click events on the outer Div, which are capture events and bubbling events, with the following code:

1 varBTN = document.getElementById ("Test");2 3 //Capturing Events4Btn.addeventlistener ("click",function(e) {5Alert ("Ok1");6},true);7 8 //Bubbling Event9Btn.addeventlistener ("click",function(e) {TenAlert ("OK"); One},false);

Finally, click on the inner div, pop ok1 first, then pop OK. Combined with the above schematic, the outer div is equivalent to the body in the diagram, the inner div is equivalent to the bottom div in the diagram, proving that the capture event executes first and then the bubbling event is executed.

Why emphasize clicking on the inner div? Because the DOM element that really triggers the event must be an inner layer, the outer DOM element has the opportunity to simulate the capture event and bubbling event, as seen from the schematic.

What if capturing events and bubbling events are registered on the DOM element that really triggers the event?

HTML structure as above, JS code as follows:

1 varBtninner = document.getElementById ("Testinner");2 3 //Bubbling Event4Btninner.addeventlistener ("click",function(e) {5Alert ("OK");6},false);7 8 //Capturing Events9Btninner.addeventlistener ("click",function(e) {TenAlert ("Ok1"); One},true);

Of course, or click on the inner Div, the result is the first pop OK, and then pop Ok1. In theory, the capture event should be triggered first, that is, the Ok1 is popped first, but here it is special, because we are registering on the DOM element that actually triggers the event, which is equivalent to registering on the div in the diagram, which shows the DOM element that really triggered the event, the end of the capture event, and the starting point of the bubbling event. So here is not a distinction between events, which first registered, which is executed first . In this case, the bubbling event is first registered, so it is executed first.

This applies to a number of the same kind of event, such as a sudden registration of 3 bubble events, then the order of execution in accordance with the order of registration, the first registration first execution. For example:

1 varBtninner = document.getElementById ("Testinner");2 3Btninner.addeventlistener ("click",function(e) {4Alert ("OK");5},false);6 7Btninner.addeventlistener ("click",function(e) {8Alert ("Ok1");9},false);Ten  OneBtninner.addeventlistener ("click",function(e) { AAlert ("Ok2"); -},false);

The results are, of course, pop-up OK, Ok1, Ok2.

In order to further understand the event model, there is also a scenario, if the outer div and the inner Div Register the capture event at the same time, then click on the inner Div, the outer div event must be triggered first, the code is as follows:

1 varBTN = document.getElementById ("Test");2 varBtninner = document.getElementById ("Testinner");3 4Btninner.addeventlistener ("click",function(e) {5Alert ("OK");6},true);7 8Btn.addeventlistener ("click",function(e) {9Alert ("Ok1");Ten},true);

The result is a pop-up Ok1 first.

If the outer div and the inner div are registered bubbling events, when clicking on the inner Div, it must be the Inner DIV event executed first, the same principle.

Careful readers will find that for div nesting cases, if you click on the inner Div, the outer div will also trigger the event, which seems to be problematic!

The click is obviously an inner div, but the event of the outer div is also triggered, which is really a problem.

In fact, when the event is triggered, it is passed by default to an event object, which is mentioned in the front, there is a method on this event object: Stoppropagation, this method can prevent bubbling, so that the outer div will not receive the event. The code is as follows:

1 varBTN = document.getElementById ("Test");2 varBtninner = document.getElementById ("Testinner");3 4Btn.addeventlistener ("click",function(e) {5Alert ("Ok1");6},false);7 8Btninner.addeventlistener ("click",function(e) {9   //Stop bubblingTen e.stoppropagation (); OneAlert ("OK"); A},false);

Finally, I want to talk about how to relieve the incident. De-event syntax: Btn.removeeventlistener ("event name", "Event callback", "Capture/bubble");

This is the same as the parameters for the binding event, which is explained in detail:

· The name of the event, which means which event to dismiss.

· An event callback is a function that must be the same as the function that registers the event.

· Event Type, Boolean, which must be the same type as when registering the event.

In other words, the name, callback, type, the three jointly decide which event to release, indispensable. As an example:

1 varBTN = document.getElementById ("Test");2 //store callbacks in a variable3 varfn =function(e) {4Alert ("OK");5 };6 //binding7Btn.addeventlistener ("Click", FN,false);8 9 //liftedTenBtn.removeeventlistener ("Click", FN,false);

If the event to be registered can be dismissed, the callback function must be saved, otherwise it cannot be lifted.

DOM0 and DOM2 Mixing

Things have been very messy, this is a mixed use, but also let people live ...

Don't be afraid, mixed use is no problem, DOM0 model and DOM2 model each follow their own rules, do not affect each other.

On the whole, which is still the first registration, which is executed first, the other is nothing.

Postscript

At this point, the original JS event has been said almost, side dishes only know these, welcome readers to supplement other knowledge points.

In practice, real pros don't really register for so many events, and in general, simply register an event in the outermost DOM element and then capture, bubble mechanism to find the DOM element that really triggered the event, and finally invoke the callback based on the information provided by the DOM element that triggered the event.

In other words, the expert will manage the incident by itself, and not rely on the browser to manage, so that can improve efficiency, and ensure compatibility, jquery is not the way to do it ~

Well, the tutorial is over, hope to help readers!

Hand Cramp in ...

Native JavaScript Event details

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.