How to customize an EventEmitter in node.js

How to customize an EventEmitter in node.js

Preface

Recently, there is a demand for wholesale goods. We need to select corresponding wholesale goods for different merchants and display them back to the original interface. Since the code of the project is at the company's antique level (this kind of code is a pain for programmers), we are very cautious when solving problems. To avoid this problem and reduce external dependencies, manually encapsulate event dispatching functions.

1. What is

We know that Node uses an event-driven mechanism, and EventEmitter is the basis for Node to implement event-driven. Based on EventEmitter, almost all modules of Node inherit this class. These modules have their own events, which can bind/trigger listeners and implement asynchronous operations.
Many objects in Node.js dispatch events. For example, the fs.readStream object triggers an event when a file is opened. These objects that generate events are instances of events.EventEmitter. These objects have an eventEmitter.on() function that is used to bind one or more functions to the named event.

2. How to use EventEmitter in nodejs

Node's events module only provides an EventEmitter class, which implements the basic pattern of Node's asynchronous event-driven architecture - the observer pattern. In this pattern, the observed (subject) maintains a group of observers sent (registered) by other objects. If a new object is interested in the subject, it registers the observer, and if it is not interested, it unsubscribes. If the subject is updated, it notifies the observers in turn.

const EventEmitter = require('events')
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter()
function callback() {
    console.log('The event was triggered!')
}
myEmitter.on('event', callback)
myEmitter.emit('event')
myEmitter.removeListener('event', callback);

3. Implementation Process

The basic code is as follows:

//Event dispatch mechanism (function() {
    var EventDispatcher = function() {
        var EventDispatcherClosure = function() {

        };
        EventDispatcherClosure.prototype = {
            /**
             * Register event * @param {Object} key
             * @param {Object} fn
             */
            on: function(key, fn) {
                //Get the current event object var curEvents = this._getCurEvents(key);
                //First check whether the event has been registered var flag = false;
                for (var i = 0, len = curEvents.length; i < len; i++) {
                    if (curEvents[i].name == fn.name) {
                        //It has already appeared, the latest registered function is the main flag = true;
                        curEvents[i] = fn;
                        break;
                    }
                }
                if (!flag) {
                    curEvents[curEvents.length] = fn;
                }
                this._register(key, curEvents);
            },
            /**
             * Dispatching event * @param {Object} key
             * @param {Object} data
             */
            dispatch: function(key) {
                //Get the current event object var curEvents = this._getCurEvents(key);
                var shouldDispatch = true;
                for (var i = 0, len = curEvents.length; shouldDispatch && i < len; i++) {
                    try {
                        //Get parameters var args = [];
                        for (var j = 1, len1 = arguments.length; j < len1; j++) {
                            args.push(arguments[j]);
                        }
                        shouldDispatch = curEvents[i].apply({}, args);
                    } catch (e) {
                        shouldDispatch = false;
                    }
                }
                return shouldDispatch;
            },
            remove: function(key) {
                if (this._getCurEvents(key)) {
                    delete EventDispatcherClosure.events[key];
                }
            },
            /**
             * Get event list based on key * @param {Object} key
             */
            _getCurEvents: function(key) {
                return EventDispatcherClosure.events[key] || [];
            },
            /**
             * Registration time* @param {Object} key
             * @param {Object} events
             */
            _register: function(key, events) {
                EventDispatcherClosure.events[key] = events;
            },
        };
        EventDispatcherClosure.events = {};
        return {
            create: function() {
                return new EventDispatcherClosure();
            }
        };
    };
    window.EventDispatcher = new EventDispatcher().create();
})();

First, define an anonymous function of a global variable, and then hang the global variable on the window, so that we can call it during the development process. Add event distribution, event monitoring, event deletion and other methods to the prototype chain of the anonymous function.

Event dispatch call

EventDispatcher.dispatch("test", obj)

Event Listening

EventDispatcher.on("test", function callback(obj) {
})

Event Deletion

EventDispatcher.on("test")

The code encapsulation is relatively simple

This is the end of this article about how to customize the implementation of an EventEmitter in node.js. For more information about implementing EventEmitter in node, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Learning Node.js from scratch series tutorial 6: Example of how EventEmitter sends and receives events
  • Introduction to the usage of Node.js events.EventEmitter
  • Instructions for using the events.EventEmitter.listenerCount method in node.js

<<:  How to use nginx to access local static resources on Linux server

>>:  Two query methods when the MySQL query field type is json

Recommend

Mycli is a must-have tool for MySQL command line enthusiasts

mycli MyCLI is a command line interface for MySQL...

Command to view binlog file creation time in Linux

Table of contents background analyze method backg...

Web Design Tutorial (3): Design Steps and Thinking

<br />Previous tutorial: Web Design Tutorial...

MySQL database operations (create, select, delete)

MySQL Create Database After logging into the MySQ...

Analysis of two implementation methods for adding static routing in Linux

Command to add a route: 1.Route add route add -ne...

Detailed explanation of how to migrate a MySQL database to another machine

1. First find the Data file on the migration serv...

Mysql backup multiple database code examples

This article mainly introduces the Mysql backup m...

Use of MySQL truncate table statement

The Truncate table statement is used to delete/tr...

A brief introduction to web2.0 products and functions

<br />What is web2.0? Web2.0 includes those ...

mysql-8.0.16 winx64 latest installation tutorial with pictures and text

I just started learning about databases recently....

Detailed explanation of three methods of JS interception string

JS provides three methods for intercepting string...

Copy and paste is the enemy of packaging

Before talking about OO, design patterns, and the ...

Simple web design concept color matching

(I) Basic concepts of web page color matching (1) ...