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

Detailed analysis of JavaScript custom events

小云云
Release: 2018-02-01 10:27:16
Original
1297 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template