Home Web Front-end JS Tutorial Detailed explanation of examples of event model in JS

Detailed explanation of examples of event model in JS

Jun 26, 2017 am 11:29 AM
javascript event Model

I was relatively clear about the event model before, and many concepts were clearly mapped in my mind. After working, on the one hand, I used
limitations, and on the other hand, I got used to using various event monitoring methods in the framework. Simplicity means convenience. Over time, some concepts of events began to fade out of my memory, just like I do now. I have begun to forget C language pointers, Maxwell's equations, matrix transformations, least squares method, etc. Knowledge is like colorful cobblestones paving the way forward, from simple to profound, from profound to understanding, always helping you go further and further. Let’s look back at the event model.


1. Brief introduction to events
Events include:Mouse eventsKeyboard events
Frame events onerror onresize onscroll Wait
Form event event onblur onfocus, etc
Clipboard event oncopy oncut onpaste
Print event onafterprint onbeforeprint
Drag event ondrag ondragenter etc.
media event onplay onpause
animation event animationend
Transition event
Other events, etc.

Events are encapsulated into objects, including
Target event object

Event listening object

Mouse event object
Keyboard event object, etc.
They contain their own properties and methods, and also inherit from the Event object. It depends on your W3C.
Commonly used methods:
event. preventDefault()//Prevent the default behavior of elements, such as link jumps and form submissions;
event. stopPropagation()//Prevent event bubbling


2. Three models of events

1. Original event model (DOM level 0)
Features: In the original event model, events There is no concept of propagation after occurrence, no event flow. When an incident occurs, handle it immediately. The listening function is just an attribute value of the element, and the listener is bound by specifying the attribute value of the element. There are two writing methods:
HTML:
js : document.getElementsById('btn').onclick = func

Advantages: All browsers are compatible

Disadvantages:

a. There is no separation between logic and display;

b. Only one listening function for the same event can be bound, and then bound will overwrite the previous one.

c. Unable to pass event bubbling, delegation and other mechanisms.

In the current modular development of web programs and more complex logic, this method is obviously outdated, so it is not recommended in real projects. It is okay to write some demos at ordinary times, and the speed is faster.

2. IE event model

Features: IE sets the event object as the attribute of window in the processing function. Once the function execution is completed, it is set to null

. IE's event model has only two steps. First, the element's listening function is executed, and then the event bubbles along the parent node to the document. Method to bind and release the listening function:
attachEvent("eventType","handler"), where evetType is the type of event, such as onclick, be sure to add
’on’.
The method to deactivate the event listener is detachEvent("eventType", "handler" );
Disadvantage: It can only be used by IE itself, which is too cold.


3. DOM2 event model

The event model is standardized in W3C Level 2 DOM events, that is, the DOM2 event model. Modern browsers (not counting IE9 and below) all

follow this specification. Features: In the event model developed by W3C, the occurrence of an event includes three processes:
a. Event capture stage. The event is propagated from the document all the way down to the target element. During this process, the passing nodes are checked in turn to see whether the listening function for the event is registered, and if so, it is executed.
b. Event processing stage. When the event reaches the target element, the event processing function of the target element is executed.
c. Event bubbling stage. The event rises from the target element until it reaches the document. It also checks whether the passing nodes have registered
the listening function for the event, and executes it if so.


Note:
All event types will go through the event capture phase, but only some events will go through the event bubbling phase. For example, the
submit event will not be bubbled.

Method to bind and release the listening function: addEventListener("eventType", "handler", "true|false"); where eventType refers to the event type, note Do not add the 'on' prefix , different from that under IE.
The second parameter is the processing function,

The third parameter is used to specify whether to enter the capture phase true during the capture phase false only the bubbling phase

The release of the listener is also similar: removeEventListner("eventType", "handler","true!false");


Compatible with IE and modern browsers event registration listening writing method

var a = document.getElementById('XXX');
if(a.attachEvent){
    a.attachEvent('onclick',func);
}
else{//IE9以上和主流浏览器
    a.addEventListener('click',func,false);
}
Copy after login

现有的框架和类库都会对适应各种浏览器做兼容性的封装,JQuery底层即使用了上面的兼容性写法。

三、事件的捕获-冒泡机制
DOM2标准中,一次事件的完整过程包括三步:捕获→执行目标元素的监听函数→冒泡,在捕获和
冒泡阶段,会依次检查途径的每个节点,如果该节点注册了相应的监听函数,则执行监听函数。

以如下HTML结构为例子,执行流程应该是这样的:

<div id="parent">
       父元素
       <div id="child">子元素</div>
</div>
Copy after login

运行一下一目了然。

var parent= document.getElementById(&#39;parent&#39;);
	console.dir(parent);
    var child = document.getElementById(&#39;child&#39;);
    parent.addEventListener(&#39;click&#39;,function(){alert(&#39;父亲在捕获阶段被点

击&#39;);},true);//第三个参数为true
    child.addEventListener(&#39;click&#39;,function(){alert(&#39;孩子被点击了&#39;);},false);
 parent.addEventListener(&#39;click&#39;,function(){alert(&#39;父亲在冒泡阶段被点击

了&#39;);},false);//第三个参数为false
Copy after login

 

  可以看到,第三个即用来指定是否在捕获阶段进 true捕获阶段,false没有捕获阶段 。
如果不想让事件向上冒泡,可以在监听函数中调用event.stopPrapagation()来完成,后面会有应
用的栗子。

四、事件委托机制

  委托就是把事件监听函数绑定到父元素上,让它的父辈来完成事件的监听,这样就把事情“委托
”了过去。在父辈元素的监听函数中,可通过event.target属性拿到触发事件的原始元素,然后
再对其进行相关处理。

 

五、jQuery中的事件监听方式
  jQuery中提供了四种事件监听方式,分别是bind、live、delegate、on,对应的解除监听的
函数分别是unbind、die、undelegate、off。这几个方法已经对各种浏览器的兼容性进行封装。
具体方法可以查看手册。
   注意几点:
   jQuery推荐事件的绑定都使使用on方法
   jQuery默认事件不在捕获中进行

六、什么是自定义事件
张鑫旭的《js-dom自定义事件》


七、一个简单例子
点击弹窗之外任何地方,弹框关闭。


方法:给body绑定事件,在事件的执行函数里关闭弹框;
     给弹框元素绑定点击事件,在事件的执行函数里面组织事件冒泡,即:
     event.stopPrapagation();

 

The above is the detailed content of Detailed explanation of examples of event model in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
The world's most powerful open source MoE model is here, with Chinese capabilities comparable to GPT-4, and the price is only nearly one percent of GPT-4-Turbo The world's most powerful open source MoE model is here, with Chinese capabilities comparable to GPT-4, and the price is only nearly one percent of GPT-4-Turbo May 07, 2024 pm 04:13 PM

Imagine an artificial intelligence model that not only has the ability to surpass traditional computing, but also achieves more efficient performance at a lower cost. This is not science fiction, DeepSeek-V2[1], the world’s most powerful open source MoE model is here. DeepSeek-V2 is a powerful mixture of experts (MoE) language model with the characteristics of economical training and efficient inference. It consists of 236B parameters, 21B of which are used to activate each marker. Compared with DeepSeek67B, DeepSeek-V2 has stronger performance, while saving 42.5% of training costs, reducing KV cache by 93.3%, and increasing the maximum generation throughput to 5.76 times. DeepSeek is a company exploring general artificial intelligence

AI subverts mathematical research! Fields Medal winner and Chinese-American mathematician led 11 top-ranked papers | Liked by Terence Tao AI subverts mathematical research! Fields Medal winner and Chinese-American mathematician led 11 top-ranked papers | Liked by Terence Tao Apr 09, 2024 am 11:52 AM

AI is indeed changing mathematics. Recently, Tao Zhexuan, who has been paying close attention to this issue, forwarded the latest issue of "Bulletin of the American Mathematical Society" (Bulletin of the American Mathematical Society). Focusing on the topic "Will machines change mathematics?", many mathematicians expressed their opinions. The whole process was full of sparks, hardcore and exciting. The author has a strong lineup, including Fields Medal winner Akshay Venkatesh, Chinese mathematician Zheng Lejun, NYU computer scientist Ernest Davis and many other well-known scholars in the industry. The world of AI has changed dramatically. You know, many of these articles were submitted a year ago.

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Hello, electric Atlas! Boston Dynamics robot comes back to life, 180-degree weird moves scare Musk Hello, electric Atlas! Boston Dynamics robot comes back to life, 180-degree weird moves scare Musk Apr 18, 2024 pm 07:58 PM

Boston Dynamics Atlas officially enters the era of electric robots! Yesterday, the hydraulic Atlas just "tearfully" withdrew from the stage of history. Today, Boston Dynamics announced that the electric Atlas is on the job. It seems that in the field of commercial humanoid robots, Boston Dynamics is determined to compete with Tesla. After the new video was released, it had already been viewed by more than one million people in just ten hours. The old people leave and new roles appear. This is a historical necessity. There is no doubt that this year is the explosive year of humanoid robots. Netizens commented: The advancement of robots has made this year's opening ceremony look like a human, and the degree of freedom is far greater than that of humans. But is this really not a horror movie? At the beginning of the video, Atlas is lying calmly on the ground, seemingly on his back. What follows is jaw-dropping

KAN, which replaces MLP, has been extended to convolution by open source projects KAN, which replaces MLP, has been extended to convolution by open source projects Jun 01, 2024 pm 10:03 PM

Earlier this month, researchers from MIT and other institutions proposed a very promising alternative to MLP - KAN. KAN outperforms MLP in terms of accuracy and interpretability. And it can outperform MLP running with a larger number of parameters with a very small number of parameters. For example, the authors stated that they used KAN to reproduce DeepMind's results with a smaller network and a higher degree of automation. Specifically, DeepMind's MLP has about 300,000 parameters, while KAN only has about 200 parameters. KAN has a strong mathematical foundation like MLP. MLP is based on the universal approximation theorem, while KAN is based on the Kolmogorov-Arnold representation theorem. As shown in the figure below, KAN has

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

FisheyeDetNet: the first target detection algorithm based on fisheye camera FisheyeDetNet: the first target detection algorithm based on fisheye camera Apr 26, 2024 am 11:37 AM

Target detection is a relatively mature problem in autonomous driving systems, among which pedestrian detection is one of the earliest algorithms to be deployed. Very comprehensive research has been carried out in most papers. However, distance perception using fisheye cameras for surround view is relatively less studied. Due to large radial distortion, standard bounding box representation is difficult to implement in fisheye cameras. To alleviate the above description, we explore extended bounding box, ellipse, and general polygon designs into polar/angular representations and define an instance segmentation mIOU metric to analyze these representations. The proposed model fisheyeDetNet with polygonal shape outperforms other models and simultaneously achieves 49.5% mAP on the Valeo fisheye camera dataset for autonomous driving

The latest from Oxford University! Mickey: 2D image matching in 3D SOTA! (CVPR\'24) The latest from Oxford University! Mickey: 2D image matching in 3D SOTA! (CVPR\'24) Apr 23, 2024 pm 01:20 PM

Project link written in front: https://nianticlabs.github.io/mickey/ Given two pictures, the camera pose between them can be estimated by establishing the correspondence between the pictures. Typically, these correspondences are 2D to 2D, and our estimated poses are scale-indeterminate. Some applications, such as instant augmented reality anytime, anywhere, require pose estimation of scale metrics, so they rely on external depth estimators to recover scale. This paper proposes MicKey, a keypoint matching process capable of predicting metric correspondences in 3D camera space. By learning 3D coordinate matching across images, we are able to infer metric relative

See all articles