Front-end implementation EventEmitter

About EventEmitter

EventEmitter Node.js is a kind of built-in module events offered, it is the core Node event stream, EventEmitter is the service side of things,
Front-end has been event-emitter of npm library
 
There are also advanced browser native API provided EventTarget this implementation and triggered event listeners
 
But they Node.js API events have more or less the difference, today we have to implement a front-end version of EventEmitter
I demo of this chapter addresses the following github
 

API Introduction 

We want to achieve the API are:
  • ON (event, listener): register a listener for a specified event, accepting a string event and a callback function.
  • EMIT (Event, [arg1], [arg2]): the order of execution of each listener listener
  • addListener (Event, listener): ON function of the same name (alias)
  • Once (Event, listener): and on similar, but only trigger once, and then they lift Event Listeners
  • removeListener (Event, listener): Removes the specified event listener a callback
  • removeAllListeners ([Event]): Removes the specified event listener all callbacks
  • setMaxListeners (n-): quantity default for improving listener. (Default 10 months listener callback a warning)
  • in the Listeners (Event): returns an array of the specified event listener.
In order to ensure compatibility and simplicity, the following syntax encoding all implemented based ES5
 

Constructor

First, we need to write a EventEmitter constructor, gives it two properties listeners and maxListener
function EventEmitter() {
    this.listeners = {};
    this.maxListener = 10;
}

listeners used to store event listener function, structure is as follows:

{
  "event1": [f1,f2,f3],
  "event2": [f4,f5],
  ...
}

The maximum number of an event maxListener is set to add a listener , beyond this value, you need to output a warning in the console, but the error will not stop. Node according to design, this value can be adjusted dynamically setMaxListeners

on methods

  1. If the number of listeners judge the event has been overrun, overrun the newspaper warning
  2. The event listener to determine whether the array initialization, if not initialized, then the listeners [event] is initialized to the array, and add listeners cb
  3. If the listener array has been initialized, it is determined whether the array already exists cb, there is no add, it exists not operate.
  4. AddListener method specified on equal
EventEmitter.prototype.on = function (event, cb) {
    var listeners = this.listeners;
    if (listeners[event] && listeners[event].length >= this.maxListener) {
        throw console.error('监听器的最大数量是%d,您已超出限制', this.maxListener)
    }
    if (listeners[event] instanceof Array) {
        if (listeners[event].indexOf(cb) === -1) {
            listeners[event].push(cb);
        }
    } else {
        listeners[event] = [].concat(cb);
    }
}

EventEmitter.prototype.addListener = EventEmitter.prototype.on;

emit method

  1. The method taken by Array.prototype.slice.call (arguments) parameter list args, (considering that simplicity and compatibility so the use of redundant coding ES5)
  2. Call args.shift kicked off the first parameter array That event, which is left to the listener to be passed
  3. Traversing the listener, to apply method by args parameter obtained above pass in
EventEmitter.prototype.emit = function (event) {
    var args = Array.prototype.slice.call(arguments);
    args.shift();
    this.listeners[event].forEach(cb => {
        cb.apply(null, args);
    });
}

 

removeListener方法

  1. By determining the listener callback indexOf array listeners [event] in position
  2. Deleted by splice (i, 1)
EventEmitter.prototype.removeListener = function (event, listener) {
    var listeners = this.listeners;
    var arr = listeners[event] || [];
    var i = arr.indexOf(listener);
    if (i >= 0) {
        listeners[event].splice(i, 1);
    }
}

once method

once on binding method is a method and removeListener methods : by listening on the method, the final position of the end of the callback, the listener function itself by deletion removeListener
EventEmitter.prototype.once = function (event, listener) {
    var self = this;
    function fn() {
        var args = Array.prototype.slice.call(arguments);
        listener.apply(null, args);
        self.removeListener(event, fn);
    }
    this.on(event, fn)
}

removeAllListener方法

Empty listeners [event] Array
EventEmitter.prototype.removeAllListener = function (event) {
    this.listeners[event] = [];
}

setMaxListeners methods and listeners method

EventEmitter.prototype.listeners = function (event) {
    return this.listeners[event];
}

EventEmitter.prototype.setMaxListeners = function (num) {
    this.maxListener = num;
}

 

Github Address

https://github.com/penghuwan/event-emitter

Guess you like

Origin www.cnblogs.com/penghuwan/p/11370120.html