Analysis of custom event usage in JavaScript_javascript skills
The examples in this article describe the usage of custom events in JavaScript. Share it with everyone for your reference. The specific analysis is as follows:
In web front-end development, many people may not use custom events of js, but if you are doing a relatively large project, especially when multiple people are developing collaboratively, custom events are very important. It's important. So, what are custom events in js? Let’s look at an example first:
Front-end developer A encapsulates a function:
alert(a); //This represents N lines of code
}
After a while, front-end developer B will enrich this function based on A, so he will write like this:
alert(a); //This represents N lines of code
alert(b); //This represents N lines of code
}
Did you find a problem? B should pay attention to naming and conflict issues with A's variables, functions, etc. After a while, front-end developer C will also enrich this function, so:
alert(a); //This represents N lines of code
alert(b); //This represents N lines of code
alert(c); //This represents N lines of code
}
It will be very frustrating at this time, and I am sure it will not be easy to write code in C. The way to solve this problem is to use custom events. We know that the same event can be added to an element without affecting each other, such as:
alert(1);
} ,false);
window.addEventListener('click',function(){
alert(2);
} ,false);
When clicking on the page, both 1 and 2 will pop up, then we can use this method to define our function:
alert(3);
} ,false);
window.addEventListener('move',function(){
alert(4);
} ,false);
In this way, when we execute move();, 3 and 4 will pop up. The move here is a custom event, which is actually a function
Let’s see how to pass parameters to the event handler:
function createFunction(obj, strFunc) {
var args = []; //Define args to store the parameters passed to the event handler
If (!obj) obj = window; //If it is a global function, obj=window;
//Get the parameters passed to the event handler
for (var i = 2; i < arguments.length; i ) args.push(arguments[i]);
//Use a parameterless function to encapsulate the call of the event handler
Return function() {
obj[strFunc].apply(obj, args); // Pass parameters to the specified event handler
}
}
function class1() {
}
class1.prototype = {
show: function() {
This.onShow();
},
onShow: function() { }
}
function objOnShow(userName) {
alert("hello," userName);
}
function test() {
var obj = new class1();
var userName = "test";
obj.onShow = createFunction(null, "objOnShow", userName);
Obj.show();
}
"Because the event mechanism only passes the name of a function without any parameter information, parameters cannot be passed in." This is something for later. "To solve this problem, you can think about it from the opposite way. No Think about how to pass parameters in, but consider how to build an event handler without parameters. This program is created based on the event handler with parameters and is an outer package. "The "program" here is createFunction. function, which cleverly uses the apply function to encapsulate functions with parameters into parameterless functions. Finally, let’s take a look at how to implement multiple bindings of custom events:
//Encapsulate functions with parameters into functions without parameters
function createFunction(obj, strFunc) {
var args = []; //Define args to store the parameters passed to the event handler
If (!obj) obj = window; //If it is a global function, obj=window;
//Get the parameters passed to the event handler
for (var i = 2; i < arguments.length; i ) args.push(arguments[i]);
//Use a parameterless function to encapsulate the call of the event handler
Return function() {
obj[strFunc].apply(obj, args); // Pass parameters to the specified event handler
}
}
function class1() {
}
class1.prototype = {
show: function() {
if (this.onShow) {
for (var i = 0; i < this.onShow.length; i ) {
This.onShow[i]();
}
}
},
attachOnShow: function(_eHandler) {
If (!this.onShow) { this.onShow = []; }
This.onShow.push(_eHandler);
}
}
function objOnShow(userName) {
alert("hello," userName);
}
function objOnShow2(testName) {
alert("show:" testName);
}
function test() {
var obj = new class1();
var userName = "your name";
Obj.attachOnShow(createFunction(null, "objOnShow", userName));
Obj.attachOnShow(createFunction(null, "objOnShow2", "test message"));
Obj.show();
}
We see that the basic idea of the attachOnShow method is to push the array. In fact, we can also remove the event processing function after the event execution is completed. Implement it separately below:
function createFunction(obj, strFunc) {
var args = []; //Define args to store the parameters passed to the event handler
If (!obj) obj = window; //If it is a global function, obj=window;
//Get the parameters passed to the event handler
for (var i = 2; i < arguments.length; i ) args.push(arguments[i]);
//Use a parameterless function to encapsulate the call of the event handler
Return function() {
obj[strFunc].apply(obj, args); // Pass parameters to the specified event handler
}
}
function class1() {
}
class1.prototype = {
show: function() {
if (this.onShow) {
for (var i = 0; i < this.onShow.length; i ) {
This.onShow[i]();
}
}
},
attachOnShow: function(_eHandler) { // Attach event
If (!this.onShow) { this.onShow = []; }
This.onShow.push(_eHandler);
},
detachOnShow: function(_eHandler) { // Remove event
If (!this.onShow) { this.onShow = []; }
This.onShow.pop(_eHandler);
}
}
function objOnShow(userName) {
alert("hello," userName);
}
function objOnShow2(testName) {
alert("show:" testName);
}
function test() {
var obj = new class1();
var userName = "your name";
Obj.attachOnShow(createFunction(null, "objOnShow", userName));
Obj.attachOnShow(createFunction(null, "objOnShow2", "test message"));
Obj.show();
obj.detachOnShow(createFunction(null, "objOnShow", userName));
Obj.show(); // Remove one and display the remaining one
obj.detachOnShow(createFunction(null, "objOnShow2", "test message"));
Obj.show(); // Remove both and display neither
}
I hope this article will be helpful to everyone’s JavaScript programming design.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

Classification and Usage Analysis of JSP Comments JSP comments are divided into two types: single-line comments: ending with, only a single line of code can be commented. Multi-line comments: starting with /* and ending with */, you can comment multiple lines of code. Single-line comment example Multi-line comment example/**This is a multi-line comment*Can comment on multiple lines of code*/Usage of JSP comments JSP comments can be used to comment JSP code to make it easier to read

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

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

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

How to use the exit function in C language requires specific code examples. In C language, we often need to terminate the execution of the program early in the program, or exit the program under certain conditions. C language provides the exit() function to implement this function. This article will introduce the usage of exit() function and provide corresponding code examples. The exit() function is a standard library function in C language and is included in the header file. Its function is to terminate the execution of the program, and can take an integer

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.

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or
