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

Linux command line quick tips: How to locate a file

We all have files stored on our computers -- dire...

How to manually deploy war packages through tomcat9 on windows and linux

The results are different in Windows and Linux en...

Notes on using the blockquote tag

<br />Semanticization cannot be explained in...

JavaScript implements page scrolling animation

Table of contents Create a layout Add CSS styles ...

Detailed steps to configure MySQL remote connection under Alibaba Cloud

Preface As we all know, by default, the MySQL ins...

Analysis and solution of flex layout collapse caused by Chrome 73

Phenomenon There are several nested flex structur...

Detailed explanation of jquery tag selector application example

This article example shares the specific code of ...

The easiest way to install MySQL 5.7.20 using yum in CentOS 7

The default database of CentOS7 is mariadb, but m...

MySQL 8.0.12 installation and configuration graphic tutorial

Recorded the download and installation tutorial o...

Pull-down refresh and pull-up loading components based on Vue encapsulation

Based on Vue and native javascript encapsulation,...

jQuery+swiper component realizes the timeline sliding year tab switching effect

Result: Implementation code: Need to be used with...

Solve the abnormal error when building vue environment with webpack

Table of contents First, configure package.json T...

The magic of tbody tag speeds up the display of table content

You must have saved other people’s web pages and l...

Docker volumes file mapping method

background When working on the blockchain log mod...