// 发布订阅模式
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) => { // 对once进行包裹,执行完就移除,实现只执行一次的效果
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;