search
HomeWeb Front-endJS TutorialDetailed explanation of examples of event model in JS

Detailed explanation of examples of event model in JS

Jun 26, 2017 am 11:29 AM
javascripteventModel

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);
}

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

 

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

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

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

运行一下一目了然。

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

 

  可以看到,第三个即用来指定是否在捕获阶段进 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
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.