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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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