function EventEmitter() {
this.events = {}
this._maxListener = 10;
}
EventEmitter.prototype.on = EventEmitter.prototype.addListener = function(type,listener) {
if (this.events[type]) {
this.events[type].push(listener);
if (this.events[type].length != 0 && this.events[type].length > this._maxListener) {
console.error(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${this.events[type].length} ${type} listeners added. Use emitter.setMaxListeners() to increase limit`)
}
} else {
this.events[type] = [listener];
}
}
EventEmitter.prototype.emit = function(type,...args) {
this.events[type] && this.events[type].forEach((item,index) => {
item(...args);
})
}
EventEmitter.prototype.once = function(type,listener) {
const wrapper = (...args) => {
listener(...args);
this.removeListener(type, wrapper);
}
this.on(type,wrapper);
}
EventEmitter.prototype.removeListener = EventEmitter.prototype.off = function(type,listener) {
if (this.events[type]) {
this.events[type] = this.events[type].filter(l => l != listener);
} else {
console.error('no listener is able to remove');
}
}
EventEmitter.prototype.removeAllListeners = function(...type) {
console.log(type)
type.forEach(t => {
this.events[t] = null;
})
}
EventEmitter.prototype.setMaxListener = function(maxListener) {
this._maxListener = maxListener;
}
EventEmitter.prototype.listeners = function(type) {
return this.events[type];
}
EventEmitter.prototype.getMaxListener = function() {
return this._maxListener;
}
EventEmitter.prototype.listenerCount = function(type) {
return this.events[type] ? this.events[type].length : 0;
}
module.exports = EventEmitter;