Custom event usage analysis in JavaScript

  • 2020-05-09 18:05:11
  • OfStack

This example demonstrates the use of custom events in JavaScript. Share with you for your reference. The specific analysis is as follows:

In web front-end development, many people may not use js's custom events, but if you're working on a relatively large project, especially if you're working with multiple people, custom events are important. So, what is a custom event in js? Let's start with an example:
Front-end developer A encapsulates a function:

function move(){
    alert(a);  // In order to represent N Lines of code
}

Over time, the front-end developer B wants to enrich this function on top of A, so he writes something like this:
function move(){
    alert(a);  // In order to represent N Lines of code
    alert(b);  // In order to represent N Lines of code
}

Is there a problem? B should pay attention to the naming and conflicts with A's variables, functions and so on. After a while, front-end developer C should also enrich this function.
function move(){
    alert(a);  // In order to represent N Lines of code
    alert(b);  // In order to represent N Lines of code
    alert(c);  // In order to represent N Lines of code
}

It's going to be crazy at this point, and I'm sure C won't have an easy time writing code. The way to solve this problem is through custom events, we know that the same events can be added to an element without their respective effects, such as:
window.addEventListener('click',function(){
    alert(1);
} ,false);
window.addEventListener('click',function(){
    alert(2);
} ,false);

When you click on the page, 1 and 2 will pop up, so we can define our function in this way:
window.addEventListener('move',function(){
    alert(3);
} ,false);
window.addEventListener('move',function(){
    alert(4);
} ,false);

In this way, we execute move(); I'm going to pop up 3 and 4 here, move is a custom event, it's just a function

Here's how to pass parameters to an event handler:

// Encapsulate a function with parameters into a function without parameters  
function createFunction(obj, strFunc) {
    var args = [];       // define args Used to store the parameters passed to the event handler
    if (!obj) obj = window; // If it's a global function obj=window;
    // Gets the parameters passed to the event handler
    for (var i = 2; i < arguments.length; i++) args.push(arguments[i]);
    // Encapsulates the call to an event handler with a parameterless function
    return function() {
        obj[strFunc].apply(obj, args); // Passes 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 transfer the name of a function with no parameters information, so I can't pass parameters into", this is another story, "we can solve this problem, from the opposite idea to think about, don't consider how to hand in the parameters, but considering how to build one event handlers without parameters, the program is based on the parameters of the event handler to create, is one of the outer packaging." , the "program" here is the createFunction function, which cleverly USES the apply function to encapsulate a function with parameters into a function without parameters. Finally, let's look at how to implement multiple bindings for custom events:

//  Enables custom events to support multiple bindings 
// Encapsulate a function with parameters into a function without parameters
function createFunction(obj, strFunc) {
    var args = [];       // define args Used to store the parameters passed to the event handler
    if (!obj) obj = window; // If it's a global function obj=window;
    // Gets the parameters passed to the event handler
    for (var i = 2; i < arguments.length; i++) args.push(arguments[i]);
    // Encapsulates the call to an event handler with a parameterless function
    return function() {
        obj[strFunc].apply(obj, args); // Passes 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();
}

As we can see, the basic idea of the attachOnShow method implementation is the push operation on the array. In fact, we can also remove the event handler function after the completion of the event execution. The following is a separate implementation:
// Encapsulate a function with parameters into a function without parameters  
function createFunction(obj, strFunc) {
    var args = [];       // define args Used to store the parameters passed to the event handler
    if (!obj) obj = window; // If it's a global function obj=window;
    // Gets the parameters passed to the event handler
    for (var i = 2; i < arguments.length; i++) args.push(arguments[i]);
    // Encapsulates the call to an event handler with a parameterless function
    return function() {
        obj[strFunc].apply(obj, args); // Passes 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) { // Additional events
        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 1 One, show the rest 1 a
    obj.detachOnShow(createFunction(null, "objOnShow2", "test message"));
    obj.show(); // Remove both, 1 None of them are shown
}

Hope that this article described the javascript programming for you to help.


Related articles: