Home Web Front-end JS Tutorial What is JavaScript event stream and event handler explained in detail

What is JavaScript event stream and event handler explained in detail

Jul 24, 2017 pm 03:42 PM
javascript js deal with

The interaction between JS and HTML is achieved through events. Events are specific moments of interaction that occur within a document or browser window. You can use listeners (or handlers) to schedule events so that appropriate code is executed when the event occurs. Known as the Observer pattern in traditional software engineering, this supports loose coupling between the behavior of the page and the appearance of the page.

Event flow

Event flow describes the order in which events are received from the page.

Event bubbling

The event is initially received by the most specific element (the node with the deepest nesting level in the document), and then Levels are propagated upward to less specific nodes (documents). Take the following HTML page as an example. If you click a button on the page, the "click" event will be propagated in the order of < button>, < body>, < html>, and document. In other words, event bubbling means that the event propagates upward along the DOM tree from the underlying element that triggered the event to the document object.


<html>
 <head>
  <title>Test</title>
 </head>
 <body>
  <button id="myBtn">A Btn</button>
 </body>
</html>
Copy after login

Event capture

Contrary to the idea of ​​event bubbling, the idea of ​​event capture is not Nodes that are too specific should receive events earlier, and nodes that are most specific should receive events last. Still in the above example, after clicking the button on the page, the "click" event will be propagated in the order of document, < html>, < body>, < button>. In other words, event capture means that the event propagates downwards along the DOM tree from the document object until the actual target element of the event.

DOM event flow

The events specified by "DOM2-level events" include three stages: event capture stage, target stage and event risk bubble stage. The first thing that happens is event capture, which provides the opportunity to intercept the event. Then the actual target receives the event. The final phase is the bubbling phase, where you can respond to events.

Still taking the previous click button as an example, in the DOM event flow, during the capture phase, the "click" event is passed from the document down to the body element (note that the actual target button will not receive it during the capture phase event). In the target phase, the button element receives the "click" event. Finally, in the bubbling phase, the event is propagated back to the document.

Event handler

An event is a certain action performed by the user or the browser itself, and the function that responds to an event is called an event handler or event listener device.

HTML event handler

The HTML event handler here refers to the event defined directly in the HTML element through attributes. handler, see the code example below. In this case, the event handler will create a function that encapsulates the element's attribute value, and this value is equal to the target element of the event. Specifying event handlers in this way has several disadvantages and is not recommended.


<button onclick="alert(&#39;HaHa~&#39;)">Btn-1</button>
<button onclick="alert(&#39;event.type&#39;)">Btn-2</button>
<button onclick="handler()">Btn-3</button>
<script type="text/javascript">
 function handler() {
  alert("Haha~");
 }
</script>
Copy after login

DOM Level 0 Event Handler

The traditional way to specify an event handler through JS is to A function is assigned to an event handler property, see the code example below. Event handlers specified this way run within the scope of the element, with this referring to the current element. Event handlers added in this way will be processed during the bubbling phase of the event flow. If you want to delete the event, just set the value of onclick to empty.


var btn = document.getElementById("myBtn");
btn.onclick = function() {
 console.log("this.id"); // "myBtn"
};
// 删除事件处理程序
btn.onclick = null;
Copy after login

DOM2-level event handler

"DOM2-level event" defines two methods with For specifying and removing event handlers, addEventListener() and removeEventListener(). These two methods are included in all DOM nodes. Both methods receive 3 parameters, the event to be processed, the processing function, and the Boolean value. The final Boolean value means that the event handler is called during the capture phase when true, and false when the event handler is called during the bubbling phase. Like the DOM0-level methods, the event handler added here also runs in the scope of the element to which it is attached. The advantage of adding event handlers using the DOM2-level method is that you can add multiple event handlers. These event handlers are fired in the order they were added. The following is a code example:


var btn = document.getElementById("myBtn");
// 添加,触发点击事件时先输出"myBtn"再输出"HaHa~"
btn.addEventListener("click", function() {
 console.log(this.id);
}, false);
btn.addEventListener("click", function() {
 console.log("HaHa~");
}, false);
Copy after login

Events added through addEventListener() can only be removed through removeEventListener(). The parameters passed in when deleting should be consistent with the parameters used when adding. This also means that the anonymous function added through addEventListener() cannot be deleted, because the anonymous function passed when adding cannot be passed to removeEventListener(). Even if an identical function is written when deleting, this function is just a New anonymous function. Please see the following code example:


var btn = document.getElementById("myBtn");
// 无法删除匿名函数
btn.addEventListener("click", function() {
 console.log(this.id);
}, false);
btn.removeEventListener("click", function() {
 console.log(this.id);
}, false);

// 正确的添加和删除方式
function handler() {
 console.log(this.id);
}
btn.addEventListener("click", handler, false);
btn.removeEventListener("click", handler, false);
Copy after login

大多数情况下,都是将事件处理程序添加到事件流的冒泡阶段,这样可以最大限度地兼容各种浏览器。最好只在需要在事件到达目标之前截获它的时候才将事件处理程序添加到捕获阶段。JS高级程序设计上给出的建议是,如果不是特别需要,不建议在事件捕获阶段注册事件处理程序。

IE事件处理程序

IE实现了与DOM中类似的两个方法: attachEvent()和deleteEvent()。这两个方法接收两个参数,事件处理程序名称和事件处理程序。注意,第一个参数是事件处理程序名称而不是事件名称,也就是说在注册点击事件的处理程序时应该传入”onclick”而不是”click”,这里跟DOM的方法有些差别。另外,这两个方法注册的事件处理程序是在全局作用域中运行而不是元素作用域,this的值指向window。还有一点需要特别小心,通过attachEvent()方法也可以添加多个事件处理程序,但是它们的执行顺序却不是按照它们被添加的顺序,而是完全相反,跟DOM方法截然不同。突然觉得IE真的特别反人类~~~下面是代码示例:


var btn = document.getElementById("myBtn");
function handler1() { // ... }
function handler2() { // ... }
// 添加,触发点击事件时先执行handler2再执行handler1
btn.attachEvent("onclick", handler1);
btn.attachEvent("onclick", handler2);
// 删除
btn.deleteEvent("onclick", handler1);
btn.deleteEvent("onclick", handler2);
Copy after login

The above is the detailed content of What is JavaScript event stream and event handler explained in detail. 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 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
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
The operation process of WIN10 service host occupying too much CPU The operation process of WIN10 service host occupying too much CPU Mar 27, 2024 pm 02:41 PM

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

A quick guide to CSV file manipulation A quick guide to CSV file manipulation Dec 26, 2023 pm 02:23 PM

Quickly learn how to open and process CSV format files. With the continuous development of data analysis and processing, CSV format has become one of the widely used file formats. A CSV file is a simple and easy-to-read text file with different data fields separated by commas. Whether in academic research, business analysis or data processing, we often encounter situations where we need to open and process CSV files. The following guide will show you how to quickly learn to open and process CSV format files. Step 1: Understand the CSV file format First,

Learn how to handle special characters and convert single quotes in PHP Learn how to handle special characters and convert single quotes in PHP Mar 27, 2024 pm 12:39 PM

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

How to solve the problem after the upgrade from win7 to win10 fails? How to solve the problem after the upgrade from win7 to win10 fails? Dec 26, 2023 pm 07:49 PM

If the operating system we use is win7, some friends may fail to upgrade from win7 to win10 when upgrading. The editor thinks we can try upgrading again to see if it can solve the problem. Let’s take a look at what the editor did for details~ What to do if win7 fails to upgrade to win10. Method 1: 1. It is recommended to download a driver first to evaluate whether your computer can be upgraded to Win10. 2. Then use the driver test after upgrading. Check if there are any driver abnormalities, and then fix them with one click. Method 2: 1. Delete all files under C:\Windows\SoftwareDistribution\Download. 2.win+R run "wuauclt.e

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles