// 建立一个类event
function Event () {
this._maxListeners = 10;
this._events = Object.create(null); // 对象存在属性:对象 值:事件数组
}
//添加事件函数
Event.prototype.addListener = function (event, callback) {
if (!this._events) {
this._events = Object.create(null);
}
if (!this._events[event]) {
this._events[event] = [callback];
} else if (this._events[event].length < this._maxListeners) {
this._events[event].push(callback);
}
}
// 移除某个事件,第二个参数为空的话表示,移除整个事件
Event.prototype.removeListener = function (event, callback) {
// 先判断该事件是否存在回调函数,即函数数组
if (Array.isArray(this._events[event])) {
// 判断参数callback是否为空
if (!callback) {
delete this._events[event];
}else {
// 删除对应事件的回调函数 删除一次执行函数的时候考虑origin
this._events[event] = this._events[event].filter(cb => cb !== callback && cb.origin !== callback);
}
}
}
// 事件触发
Event.prototype.emit = function (event, ...args) {
let callbacks = this._events[event];
if (Array.isArray(callbacks)) {
callbacks.forEach((cb) => {
cb.apply(this, args);
})
}
}
// 一次执行事件
Event.prototype.once = function (event, callback) {
const only = function (...args) {
callback.apply(this, args);
this.removeListener(event, callback);
}
only.origin = callback;
this.addListener(event, only);
}
// 设置最大参数
Event.prototype.setMaxCallbackNum = function (num) {
this._maxListeners = num;
}
//引入events
var events = new Event();
//定义事件1
var listener1 = function listener1 () {
console.log('这是监听器1');
}
// 定义事件2
var listener2 = function listener2 () {
console.log('这是监听器2');
}
// 为connection事件添加listener1回调函数
events.addListener('connection', listener1);
// events.setMaxCallbackNum(1);
events.once('connection', listener2);
events.emit('connection');
events.removeListener('connection', listener1);
events.emit('connection');