Deep analysis of native JavaScript events _ basics

Source: Internet
Author: User
Tags mixed

jquery This write less do more frame, with a lot of will inevitably to native JS Yangaoshoudi.

Small dishes In fact do not want to write this blog, seemingly very elementary appearance, but see the network even the original JS event binding and lifting all said not understand, or decided to science a bit.

First of all, the side dishes understand is not a lot, just to share my thoughts with you.

DOM0 Event Model

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

The DOM0 event model is supported by all browsers.

Registering an event name directly on a DOM object is DOM0 writing, such as:

Copy Code code as follows:

document.getElementById ("Test"). onclick = function (e) {};

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

Copy Code code as follows:

document.getElementById ("Test") ["onmousemove"] = function (e) {};

It's nothing, is just two ways to access the properties of JS object, [] The form is mainly to solve the property name is not a valid identifier, such as: object.123 affirmation error, but object["123"] to avoid this problem, at the same time, [] The writing, also put JS write live, The property name is represented by a string, and the event can be dynamically bound at run time.

To get to the point, when an event is triggered, a parameter e is passed in by default, representing the event object, through E, we can obtain a lot of useful information, such as the coordinates of the click, the DOM element that triggers the event, and so on.

Based on DOM0 events, for the same DOM node, you can only register one, and the same event that is registered after it overwrites the previously registered. For example:

Copy Code code as follows:

var btn = document.getElementById ("test");
Btn.onmousemove = function (e) {
Alert ("OK");
};
btn["onmousemove"] = function (e) {
Alert ("Ok1");
};

The result is output ok1.

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

Copy Code code as follows:

var btn = document.getElementById ("test");
Btn.onmousemove = function (e) {
alert (this.id);
};

Results output test. Because the event is registered on a DOM node with the ID test, this, of course, represents the DOM node when the event is triggered, and it can be understood that the event was invoked by this DOM node.

So, it's fairly easy to dismiss an event, you just need to register one more event and set the value to NULL, for example:

Copy Code code as follows:

var btn = document.getElementById ("test");
Btn.onclick = function (e) {
Alert ("OK");
};
Btn.onclick = null;

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

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

Copy Code code as follows:

<div id= "test" class= "test" onclick= "exec ();" ></div>

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

The difference is that the registered event is equivalent to a dynamic call function (a bit of an eval), so it does not pass in the event object, and this points to window and is no longer a DOM object that triggers the event.

DOM2 Event Model

The DOM2 event model, relative to DOM0, only understands the following two points:

· DOM2 supports registering multiple homogeneous events with the same DOM element.

· DOM2 has added the concept of capture and bubbling.

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

But IE8 and the following version of the browser, to amuse themselves, made a corresponding attachevent and detachevent, due to the side dishes talents, this article does not discuss.

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

Copy Code code as follows:

var btn = document.getElementById ("test");
Btn.addeventlistener ("click", Function (e) {
Alert ("OK");
}, False);

The event name is needless to say, compared to DOM0, the front is removed.

The event callback is also very well understood, the event triggers must inform you! The callback, like DOM0, also defaults to an event parameter, and this is the DOM node that triggers the event.

The last argument is a Boolean, and true represents the capture event, and false represents the bubbling event. Actually very good understanding, first come to a schematic:

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

Why do you design this way? This seems to be due to the deep historical origins, small dishes also do not understand, it is not nonsense.

As you can see, capturing events is triggered first than bubbling events.

Suppose you have such an HTML structure:

Copy Code code as follows:

<div id= "test" class= "Test" >
<div id= "Testinner" class= "Test-inner" ></div>
</div>

Then we register the two click events on the outer Div, capturing events and bubbling events, respectively, as follows:

Copy Code code as follows:

var btn = document.getElementById ("test");
Capturing events
Btn.addeventlistener ("click", Function (e) {
Alert ("Ok1");
}, True);
Bubbling events
Btn.addeventlistener ("click", Function (e) {
Alert ("OK");
}, False);

Finally, click on the inner Div, first pop-up ok1, and then pop OK. Combined with the schematic above, the outer div is equivalent to the body in the diagram, the inner div is the same as the bottom div, proof that the capture event executes first, and then executes the bubbling event.

Why should you 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 the bubbling event, as you can see from the schematic diagram.

What if the capture event and bubbling event are registered on the DOM element that actually triggers the event?

HTML structure ibid., JS code as follows:

Copy Code code as follows:

var Btninner = document.getElementById ("Testinner");
Bubbling events
Btninner.addeventlistener ("click", Function (e) {
Alert ("OK");
}, False);
Capturing events
Btninner.addeventlistener ("click", Function (e) {
Alert ("Ok1");
}, True);

Of course, click on the inner Div, the result is to pop OK, then pop Ok1. In theory, the capture event should be triggered first, that is, the first pop-up Ok1, but here is more special, because we are in the real trigger event of the DOM elements registered on the event, the equivalent of the DIV on the graph registered, the graph can see the real trigger event DOM element, is to catch the end of the event, is the starting point of bubbling events, So here is no distinction between the event, which first registered, the first to execute which. In this case, the bubbling event is registered first, so it executes first.

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

Copy Code code as follows:

var Btninner = document.getElementById ("Testinner");
Btninner.addeventlistener ("click", Function (e) {
Alert ("OK");
}, False);
Btninner.addeventlistener ("click", Function (e) {
Alert ("Ok1");
}, False);
Btninner.addeventlistener ("click", Function (e) {
Alert ("Ok2");
}, False);

The result, of course, is to pop OK, Ok1, and Ok2 in turn.

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, then click on the inner Div, the outer div event must be triggered first, the code is as follows:

Copy Code code as follows:

var btn = document.getElementById ("test");
var Btninner = document.getElementById ("Testinner");
Btninner.addeventlistener ("click", Function (e) {
Alert ("OK");
}, True);
Btn.addeventlistener ("click", Function (e) {
Alert ("Ok1");
}, True);

The result is to eject the Ok1 first.

If the outer div and inner div are registered bubble events, click on the inner Div, it must be inside the Div event first executed, the principle is the same.

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

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

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

Copy Code code as follows:

var btn = document.getElementById ("test");
var Btninner = document.getElementById ("Testinner");
Btn.addeventlistener ("click", Function (e) {
Alert ("Ok1");
}, False);
Btninner.addeventlistener ("click", Function (e) {
Block bubbling
E.stoppropagation ();
Alert ("OK");
}, False);

Finally to talk about how to disarm the incident. Dismiss event Syntax: Btn.removeeventlistener (event name, event callback, capture/bubbling);

This is the same as the parameter of the binding event, which is described in detail:

· Event name, that is, which event to dismiss.

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

That is to say, name, callback, type, the three together decide which event to release, indispensable. As an example:

Copy Code code as follows:

var btn = document.getElementById ("test");
To store callbacks in a variable
var fn = function (e) {
Alert ("OK");
};
Binding
Btn.addeventlistener ("Click", FN, false);
Lifted
Btn.removeeventlistener ("Click", FN, false);

If you want to register an event that can be lifted, you must save the callback function, 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 perfectly fine, the DOM0 model and the DOM2 model each follow their own rules and do not affect each other.

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

Postscript

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

In practical applications, a real connoisseur is not going to fool around really registering so many events, in general, simply register an event in the outermost DOM element, then find the DOM element that really triggers the event by capturing and bubbling the mechanism, and then invoke the callback based on the information provided by the DOM element that triggered the event.

In other words, the experts will manage their own events, 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, this is the end of the tutorial, I hope to help readers!

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.