preface

Recently, I made the demand of commodity wholesale, which needs to select corresponding wholesale commodities for different merchants and display them to the original interface. Because the code on the project was a company antique (code that was a pain in the ass), the problems were solved with great care. To avoid this problem and reduce external dependencies, manually encapsulate event-dispatched functions.

What is it

EventEmitter is the base for Node to implement EventEmitter. Almost all modules in Node inherit EventEmitter. These modules have their own events and can bind/fire listeners. Many objects in Node.js emit events, such as the fs.readStream object, which fires an event when a file is opened. These objects are instances of events.EventEmitter. These objects have an eventEmitter. On () function that binds one or more functions to named events

2. Use method of EventEmitter in NodeJS

The Events module of Node provides an EventEmitter class that implements the basic Node asynchronous event-driven architecture. In this mode, an observer maintains a group of observers sent by other objects, and registers observers when new objects are interested in the subject. Unsubscribe if you’re not interested, and notify observers in turn of updates

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

Third, the 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);
                // Check if the event is already registered
                var flag = false;
                for (var i = 0, len = curEvents.length; i < len; i++) {
                    if (curEvents[i].name == fn.name) {
                        // It already exists, mainly for newly registered functions
                        flag = true;
                        curEvents[i] = fn;
                        break; }}if(! flag) { curEvents[curEvents.length] = fn; }this._register(key, curEvents);
            },
            /** ** Send 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)) {
                    deleteEventDispatcherClosure.events[key]; }},/** * Get the list of events by 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 newEventDispatcherClosure(); }}; };window.EventDispatcher = newEventDispatcher().create(); }) ();Copy the code

First define an anonymous function for the global variable, and then hang the global variable above the window so that we can call it during development. Add event distribution, event listening, event deletion, and so on to the prototype chain of anonymous functions.

Call for event distribution

EventDispatcher.dispatch("test", obj)
Copy the code

Event listeners

EventDispatcher.on("test".function callback(obj) {})Copy the code

Delete events

EventDispatcher.on("test")
Copy the code

The code package is relatively simple, I hope the big guy read a thumbs up and then go. Thanks!!