JavaScript-deep event mechanism

Source: Internet
Author: User

Yuyuyu
Links: https://zhuanlan.zhihu.com/p/24620643
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

1.1 How event bindings are

There are several ways to bind native JS events. There must be a lot of friends say 3 kinds! At present, in my current study, there are only two kinds of half! Two kinds of half? Half a kind? And listen to my word.

It is estimated that three of the three kinds of people are considered as follows:

// 第一种:直接绑定在dom上<div onclick="fun();">click</div>
// 第二种,使用onclickdocument.getElementById("xxx").onclick = function(){};
// 第三种:使用推荐的标准模式document.getElementById("xxx").addEventListener("click",function(e){});

Indeed, this is the most three ways to search the Internet, but there is a pit, that is, when you use three at the same time, the second will be the first to cover out, that is, the first and the second is the same way, but the wording is different, we can write a demo for the card:

<! DOCTYPE html><Html><Head><MetaCharSet="UTF-8"></Head><Body><buttonId="BTN1"OnClick="Fun1 ();">btn</button></Body><ScriptType="Text/javascript">functionFun1(){Console.Log("111");}VarBtn=Document.getElementById( "btn1" ); btn. OnClick = function () {console.< Span class= "NX" >log ( "222" } btn. Addeventlistener ( "click" ,function  () {console. Log (</script></html< Span class= "P" >>               

Read my other blog in-depth understanding of document's children's shoes should know that the onclick is a property on the elenent. The so-called attribute means that there is only one, and repeated assignments overwrite the previous one. But AddEventListener does not, this method binds multiple event programs and executes sequentially.


So what's the rest of the half-way? I went straight to the code, after all, the program ape is an animal that understands the ability to code more than the ability to understand words:

<! DOCTYPE html><Html><Head><MetaCharSet="UTF-8"></Head><Body><AId="BTN1"OnClick="Fun1 ();"Href="Javascript:fun2 ();">btn</A></Body><ScriptType="Text/javascript">functionFun1(){Console.Log("111");}functionFun2(){Consolelog (} var btn = document. Getelementbyid (. Addeventlistener ( "click" ,function  () {console. Log (</script></html< Span class= "P" >>               

This explains why it is half-way, because the use of the scene is very limited, many labels can not be used. This time careful you may find that the order here is also expected to be different, for this is the next topic, JS event execution sequence.


1.2 Execution order of events

Demo code will not write, code too much, interested can directly copy the above you to modify, I said I came to the conclusion that

    • The code in the href of a tag is always last executed, with the lowest priority.
    • The order of execution, either the onclick or the AddEventListener, is executed in the order in which it is bound, or first bound.
    • If the OnClick event is repeatedly bound, the last binding is in the order in which it was bound.
    • If the onclick is used directly in the DOM and there is no overwrite, the onclick binding is earlier than AddEventListener.
    • If multiple AddEventListener events are bound, stoppropagation () in any one event; Will prevent the event from bubbling, but will not prevent subsequent events from executing.

1.3 Detailed Event objects

The usual, or the first code, first look at the code and:

<! DOCTYPE html><Html><Head><MetaCharSet="UTF-8"></Head><Body><buttonId="BTN1">btn</button></Body><ScriptType= "Text/javascript" >var btn = document. Getelementbyid (. Addeventlistener ( "click" ,function  (event) {console. Log (event}); </script></html< Span class= "P" >>               

At this point the console prints a MouseEvent object, which explains a little bit:

    • ClientX, Clienty;layerx, Layery;offsetx, Offsety;pagex, Pagey;screenx, ScreenY ... Wait, these are the relative coordinates of the event trigger, relative to the browser, relative to the browser, relative to the parent element, relative to the current element, there is no more talk, you can ferry yourself.
    • Altkey, Ctrlkey, Shiftkey, Metakey: They all return Boolean values that hold the ALT key, the CTRL key, the SHIFT key, the win key, and the last meta is the win key under Windows, is located in the lower left corner of the keyboard ctrl and ALT between the key with the Windows flag, but on the Mac I did not test, the current this is not conclusive, I hope that the classmate of the Mac machine can test it to try.
    • Type: Represents the event types, which is of course clicked.
    • Target: Represents the trigger source of an event, often used when the event is bubbling, and is judged using Event.target.
    • TimeStamp: The time, in milliseconds, that the event is bound from completion to this event.
    • Path: The bubbling order of the event, indicating where the event was triggered to the end (this property has compatibility issues, I did not find this attribute in Firefox).
    • The other attributes don't have to be one, and you can read through the document with interest. (The last side of the article has an address)

This time some students may ask, I usually to prevent event bubbling and default events using the Stoppropagation and Preventdefault methods, why not here?

This question is good, because Toppropagation and Preventdefault are the method of event, and MouseEvent is indirectly inherited by the event can use this method, then where he inherited it?

We directly expand the browser console of the MouseEvent __proto__ property, pull to the bottom, found that he also has a __proto__ property, the type of the __proto__ property is Uievent, continue to expand, uievent __proto__ Is event,event inside has these two methods, familiar with JS prototype chain classmate should all know this.

Plainly, the MouseEvent inherited the event, and the event inherits the Object, Uievent,uievent. (This prototype chain spread too long, I can not, children's shoes to test themselves)


Now, do you have a whole new understanding of the event?


MouseEvent Event Document Address



(article for original, reproduced please specify the source)

JavaScript-deep event mechanism

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.