Native JavaScript event details

Source: Internet
Author: User

Native JavaScript event details
The Write Less Do More framework of JQuery is easy to use for native js. I don't really want to write this blog. It looks very basic, but I don't understand how to bind and unbind native js events on the Internet, so I decided to get a better idea. First of all, I declare that not many dishes are understood, but I just want to share my ideas with you. The DOM0 event model is evolving. The early event model is called the DOM0 level. The DOM0 event model is supported by all browsers. Register the event name directly on the dom object, that is, the DOM0 statement, such as: 1 document. getElementById ("test "). onclick = function (e) {}; indicates registering an onclick event. Of course, it and this writing mean: 1 document. getElementById ("test") ["onmousemove"] = function (e) {}; this is nothing, but it is two methods to access js object attributes, [] is mainly used to solve the problem that the attribute name is not a valid identifier. For example, object.123 certainly reports an error, but object ["123"] avoids this problem, [] writing method. js is also written, and the attribute name is represented by a string. The event can be dynamically bound at runtime. When an event is triggered, a parameter e is passed in by default to indicate the event object. Through e, we can get a lot of useful information, for example, click coordinates, dom elements that trigger the event, and so on. For a single dom node, only one DOM0-based event can be registered. The same event registered later will overwrite the previously registered event. Example: 1 var btn = document. getElementById ("test"); 2 3 btn. onmousemove = function (e) {4 alert ("OK"); 5}; 6 7 btn ["onmousemove"] = function (e) {8 alert ("ok1 "); 9}; the result will output ok1. Next, let's talk about this. When an event is triggered, this indicates the dom object on which the event is triggered. Example: 1 var btn = document. getElementById ("test"); 2 3 btn. onmousemove = function (e) {4 alert (this. id); 5}; the result output is test. Because the event is registered on the dom node with the id test. When the event is triggered, this represents the dom node. It can be understood that the event is called by the dom node. Therefore, it is quite easy to cancel the event. You only need to register the event again and set the value to null, for example, 1 var btn = document. getElementById ("test"); 2 3 btn. onclick = function (e) {4 alert ("OK"); 5}; 6 7 btn. onclick = null; the principle is that the last registered event must overwrite the previous one. If the last registered event is set to null, the event binding is unbound. The incident is not over yet. The DOM0 event model also involves events written directly in html. For example: 1 <div id = "test" class = "test" onclick = "exec ();"> </div> the event registered in this way follows the overwrite principle, you can only register one and the last one takes effect. The difference is that an event registered in this way is equivalent to calling a function dynamically (a bit eval), so the event object is not passed in. At the same time, this points to window, it is no longer the dom object that triggers the event. Compared with DOM0, The DOM2 event model has the following knowledge: · DOM2 supports registering multiple events of the same type with the same dom element. · DOM2 introduces the concept of capture and bubbling. DOM2 events are managed through addEventListener and removeEventListener. Of course, this is a standard. However, IE8 and earlier versions of browsers are entertaining and have developed the corresponding attachEvent and detachEvent. This article will not discuss this issue because it is not easy to learn. Of course, addEventListener registers an event. It has three parameters: "event name", "Event Callback", and "capture/bubble ". For example: 1 var btn = document. getElementById ("test"); 2 3 btn. addEventListener ("click", function (e) {4 alert ("OK"); 5}, false); the event name is unnecessary. Compared with DOM0, remove the on from the front. Event Callback is also easy to understand. You must be notified when an event is triggered! The callback is the same as that of DOM0, and an event parameter is passed in by default. this is the dom node that triggers the event. The last parameter is boolean. true indicates the event to be captured, and false indicates the bubble event. In fact, it is easy to understand. First, it means that an element triggers an event. The first thing to be notified is window, and then the document, this process is captured until the element (target element) that actually triggers the event. Next, the event will bubble from the target element and then exit in sequence until the window object ends. This process is bubbling. Why is it designed like this? This seems to be due to its profound historical origins, so I don't know much about cooking. It can be seen that the capture event is triggered first than the bubble event. Suppose there is such an html structure: 1 <div id = "test" class = "test"> 2 <div id = "testInner" class = "test-inner"> </div> 3 </div> and we register two click events on the outer div, capture events and bubble events respectively. The Code is as follows: 1 var btn = document. getElementById ("test"); 2 3 // capture event 4 btn. addEventListener ("click", function (e) {5 alert ("ok1"); 6}, true); 7 8 // bubble event 9 btn. addEventListener ("click", function (e) {10 alert ("OK"); 11}, false); finally, click the div in the inner layer to bring up ok1, and then click OK. Combined with the above schematic, the outer div is equivalent to the body in the figure, and the inner div is equivalent to the lower div in the figure. It proves that the capture event is executed first and then the bubble event is executed. Why do we need to emphasize clicking the div in the inner layer? Because the dom element that actually triggers an event must be an inner layer, the outer dom element has the opportunity to simulate capture events and bubble events, as shown in the schematic. What if I register a capture event and a bubble event on the dom element that actually triggers the event? The html structure is the same as above. js code is as follows: 1 var btnInner = document. getElementById ("testInner"); 2 3 // bubble event 4 btnInner. addEventListener ("click", function (e) {5 alert ("OK"); 6}, false); 7 8 // capture event 9 btnInner. addEventListener ("click", function (e) {10 alert ("ok1"); 11}, true); of course, click the inner div, and the result is that OK is displayed first, then, ok1 is displayed. In theory, capture events should be triggered first, that is, ok1 should be popped up first, but this is special, because we are registering events on the dom element that actually triggers events, it is equivalent to registering on the div in the figure. The figure shows that the dom element that actually triggers the event is the end point of the capture event and the start point of the bubble event, so events are not distinguished here, if you register the instance first, you must first execute the instance. In this example, the bubble event is registered first, so it is executed first. This principle applies to multiple events of the same type. For example, if three bubble events are registered at once, the execution order is based on the registration order. First, the registration is performed first. Example: 1 var btnInner = document. getElementById ("testInner"); 2 3 btnInner. addEventListener ("click", function (e) {4 alert ("OK"); 5}, false); 6 7 btnInner. addEventListener ("click", function (e) {8 alert ("ok1"); 9}, false); 10 11 btnInner. addEventListener ("click", function (e) {12 alert ("ok2"); 13}, false); the result is of course OK, ok1, and ok2. To further understand the event model, there is another scenario. If the outer div and the inner div register a capture event at the same time, when you click the inner div, the event of the outer div must be triggered first, the Code is as follows: 1 var btn = document. getElementById ("test"); 2 var btnInner = document. getElementById ("testInner"); 3 4 btnInner. addEventListener ("click", function (e) {5 alert ("OK"); 6}, true); 7 8 btn. addEventListener ("click", function (e) {9 alert ("ok1"); 10}, true); the result is that ok1. If both the outer div and the inner div are registered bubble events, when you click the inner div, the inner div event must be executed first. The principle is the same. Careful readers will find that, for div nesting, if you click the inner div, the outer div will also trigger the event, which seems to be a problem! Click the inner div, but the event of the outer div is also triggered, which is indeed a problem. In fact, when an event is triggered, an event object will be passed in by default, which has been mentioned before. There is a method on this event object: stopPropagation. This method can be used to prevent bubbling, in this way, the outer div cannot receive the event. The Code is as follows: 1 var btn = document. getElementById ("test"); 2 var btnInner = document. getElementById ("testInner"); 3 4 btn. addEventListener ("click", function (e) {5 alert ("ok1"); 6}, false); 7 8 btnInner. addEventListener ("click", function (e) {9 // block bubbling 10 e. stopPropagation (); 11 alert ("OK"); 12}, false); finally, let's talk about how to release the event. Cancel event Syntax: btn. removeEventListener ("event name", "Event Callback", "capture/bubble"); this is the same as the parameter for binding events. For details, see: · event name, that is, the event to be removed. · Event Callback is a function, which must be the same as the function used to register events. · Event type, Boolean value, which must be consistent with the event type when registering. That is to say, the name, callback, and type jointly determine which event to release. For example: 1 var btn = document. getElementById ("test"); 2 // store the callback in the variable 3 var fn = function (e) {4 alert ("OK"); 5 }; 6 // bind 7 btn. addEventListener ("click", fn, false); 8 9 // remove 10 btn. removeEventListener ("click", fn, false); to cancel a registered event, you must save the callback function; otherwise, the event cannot be released. The mixed use of DOM0 and DOM2 was originally messy, and this was another hybrid use, which made people not to be alive... Don't be afraid. There is no problem in mixed use. The DOM0 model and the DOM2 model follow their own rules and do not affect each other. In general, it is still the first registration, the first execution, and nothing else. At this point, the native js event has been about the same. You only need to know about this. You are welcome to add other knowledge points. In practical applications, real experts do not really register so many events. Generally, they only need to register an event on the outermost dom element, then, the dom elements that actually trigger the event are found through the capture and bubble mechanism, and the callback is called based on the information provided by the dom element of the trigger event. That is to say, experts Manage events on their own without relying on browsers. This improves efficiency and ensures compatibility. JQuery does not do this ~ Now, the tutorial is over. I hope it will be helpful to 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.