Home Web Front-end JS Tutorial Detailed analysis of JavaScript custom events

Detailed analysis of JavaScript custom events

Feb 01, 2018 am 10:27 AM
javascript js customize

This article mainly shares with you a detailed analysis of JavaScript custom events. Events are a way for users to interact with browsers. In this case, our code logic is generally to collect user-filled information, verify the legality of the information, and use AJAX Friends who need to interact with the server can refer to it. I hope it can help everyone.

Event

The technical level is generally limited. If there are any mistakes, please correct me.

Events are a way for users to interact with browsers. For example, if a user registers a function, after filling in the basic information, we can click the submit button to implement the registration function. All that is needed to complete this function is a click event. We pre-define the operation behavior, and execute our pre-determined behavior when the user clicks the submit button. In this case, our code logic is generally to collect the information filled in by the user, verify the legality of the information, and use AJAX to interact with the server.

This process is just like we usually encapsulate a function and then call the function. The event is actually a process similar to function definition and function call, except that the call of the event function is notified to the browser by some operations of the user. Let the browser call the function.

First of all, the browser has provided us with a list of events, including click, keydown, etc. Why do we need to customize events? In fact, it is a more accurate description of our behavior. Taking the user registration above as an example, we can define an event named saveMessage. This event is triggered when the submit button is clicked. It seems more intuitive, but it seems no different from an ordinary function call. Think about the function carefully. The difference between calling and event triggering is that functions executed by ourselves are function calls, and functions that are not executed by us are event triggered. Look at the following code:


window.onload = function(){
 var demo = document.getElementById("demo");
 demo.onclick = handler;
 function handler(){
  console.log("aaa");
 }
}
Copy after login

When we click the button, aaa will be printed, and it is obvious that the function is not called by us but by the browser It is executed by the handler. If we directly call the function handler(), we can print aaa, but this is called by us, so it is a function call.

The role of custom events

Custom events are functions that we customize according to the browser’s event mechanism. Custom events can bring better explanations to our processing functions, and can also bring better processing processes to our plug-ins. Suppose we have another requirement: pull a set of data from the server and display it as a list in HTML, and then identify the first piece of data. If we use an existing processing function, we may write it like this:


dataTable("url");
$("table").find("input[type='checkbox']:first").prop("checked",true);
Copy after login

This cannot achieve our purpose because JS is single-threaded and AJAX is asynchronous. When the code $("table").find("input[type= When 'checkbox']:first").prop("checked",true) is executed, the data we need has not yet been obtained. It is obviously unwise for us to modify the internal implementation of the plug-in. An acceptable plug-in must have a reasonable callback function (or custom event). If there is a callback function that successfully draws the list, we can This callback function is regarded as an event. We can add event operations to this event, define a processing function, and then let the plug-in execute this processing function when the list is drawn successfully.

Custom event implementation

We simulate the browser's native events to implement custom events (en: custom event name, fn: event processing function, addEvent: Add a custom event for the DOM element, triggerEvent: trigger a custom event):


window.onload = function(){
 var demo = document.getElementById("demo");
 demo.addEvent("test",function(){console.log("handler1")});
 demo.addEvent("test",function(){console.log("handler2")});
 demo.onclick = function(){
  this.triggerEvent("test");
 }
}
Element.prototype.addEvent = function(en,fn){
 this.pools = this.pools || {};
 if(en in this.pools){
  this.pools[en].push(fn);
 }else{
  this.pools[en] = [];
  this.pools[en].push(fn);
 }
}
Element.prototype.triggerEvent = function(en){
 if(en in this.pools){
  var fns = this.pools[en];
  for(var i=0,il=fns.length;i<il;i++){
   fns[i]();
  }
 }else{
  return;
 }
}
Copy after login

The function executed by ourselves is a function call, and the function not executed by us can be called Triggering events, since the function is not called by us, then how the caller knows which functions to call is a problem, so it is necessary to add some constraints between adding the event function and triggering the event function, that is, there are An event pool that everyone can access. When adding an event, put the event and the corresponding processing function in this pool. When the triggering conditions are met, go to the pool to find the event to be triggered and execute the corresponding processing function, so there is The piece of code we have above.

There may be many processing functions for the same function (event), so we need a collection to store these processing functions. At this time, we should reflect the two solutions JSON or array. The structure of JSON is key :value, for the processing function, the name has no effect, so we use an array to save the processing function. What functions does this set of functions handle, so we also need a description for this set of processing functions. At this time, JSON is needed. -->{eventName:[]}.

Use a simplified BootStrap modal window to demonstrate the role of custom events:


window.onload = function(){
 var show = document.getElementById("show");
 var hide = document.getElementById("hide");
 var content = document.getElementById("content");
 show.onclick = function(){
  content.modal("show");
 }
 hide.onclick = function(){
  content.modal("hide");
 }
 content.addEvent("show",function(){alert("show before")});
 content.addEvent("shown",function(){
  document.getElementById("input").focus();
  alert("show after");
 }); 
}
;(function(ep){
 ep.addEvent = function(en,fn){
  this.pools = this.pools || {};
  if(en in this.pools){
   this.pools[en].push(fn);
  }else{
   this.pools[en] = [];
   this.pools[en].push(fn);
  }
 }
 ep.triggerEvent = function(en){
  if(en in this.pools){
   var fns = this.pools[en];
   for(var i=0,il=fns.length;i<il;i++){
    fns[i]();
   }
  }else{
   return;
  }
 }
 ep.modal = function(t){
  switch(t){
   case "show":
    this.triggerEvent("show");
    this.style.display = "block";
    setTimeout(function(){this.triggerEvent("shown")}.bind(this),0);//该定时器主要是为了在视觉上先看见content,在弹出消息
    break;
   case "hide":
    this.style.display = "none";
    break;
   default:
    break;
  }
 }

}(Element.prototype));
Copy after login

We can pre-define before and after the pop-up window appears. The corresponding processing function is executed when the pop-up window triggers the corresponding event.

related suggestion:

v-on binding custom event in Vue.js component

Basic knowledge of writing custom events in JavaScript

How to create custom events in JavaScript


The above is the detailed content of Detailed analysis of JavaScript custom events. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

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

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

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