标签:http 语法 -o 数列 concat 超出 tst event ||
function EventEmitter() { this.listeners = {}; this.maxListener = 10; }
listeners用于存放事件监听器函数,结构如下:
{ "event1": [f1,f2,f3], "event2": [f4,f5], ... }
而maxListener 是设置的某个事件能够添加的监听器的最大数量,超过这个值,需要在控制台输出警告,但不会报错阻止。按照Node的设计,这个值能够通过setMaxListeners动态调整
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;
EventEmitter.prototype.emit = function (event) { var args = Array.prototype.slice.call(arguments); args.shift(); this.listeners[event].forEach(cb => { cb.apply(null, args); }); }
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); } }
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) }
EventEmitter.prototype.removeAllListener = function (event) { this.listeners[event] = []; }
EventEmitter.prototype.listeners = function (event) { return this.listeners[event]; } EventEmitter.prototype.setMaxListeners = function (num) { this.maxListener = num; }
标签:http 语法 -o 数列 concat 超出 tst event ||
原文地址:https://www.cnblogs.com/penghuwan/p/11370120.html