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

Mini Program natively implements left-slide drawer menu

Table of contents WXS Response Event Plan A Page ...

Eight implementation solutions for cross-domain js front-end

Table of contents 1. jsonp cross-domain 2. docume...

Common browser compatibility issues (summary)

Browser compatibility is nothing more than style ...

Analysis of MySQL Aborted connection warning log

Preface: Sometimes, the session connected to MySQ...

How to build a standardized vmware image for kubernetes under rancher

When learning kubernetes, we need to practice in ...

JS implements the snake game

Table of contents 1. Initialization structure 2. ...

Mysql sql slow query monitoring script code example

1. Modify my.cnf #The overall effect is that both...

What is ssh port forwarding? What's the use?

Table of contents Preface 1. Local port forwardin...

Practical method of deleting a row in a MySql table

First, you need to determine which fields or fiel...

Right align multiple elements in the same row under div in css

Method 1: float:right In addition, floating will ...

JQuery implements hiding and displaying animation effects

This article shares the specific code of JQuery t...

Navicat connection MySQL error description analysis

Table of contents environment Virtual Machine Ver...

Preventing SQL injection in web projects

Table of contents 1. Introduction to SQL Injectio...