发布订阅模式其实是一种对象间一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都将得到状态改变的通知。订阅者把自己想订阅的事件注册到调度中心,当发布者发布该事件到调度中心,也就是该事件触发时,由调度中心统一调度订阅者注册到调度中心的处理代码。
核心实现代码
// 声明EventEmitter事件发生器构造函数
function EventEmitter() {
this._events = Object.create(null);
}
//on 订阅方法实现 因为在实例上调用,所以写在原型上
EventEmitter.prototype.on = function(type,callback){
// 如果实例不存在则创建一个空对象,Object.create(null)没有链
if(!this._events) {
this._events = Object.create(null);
}
if(this._events[type]){ //如果失恋有对应的值,直接往数组push
this._events[type].push(callback)
}else { //第一次订阅,没有失恋,就声明{失恋:[cry]}
this._events[type] = [callback];
}
};
// emit方法实现
EventEmitter.prototype.emit = function(type){
if(this._events[type]){ //{失恋:[cry,eat]} 如果失恋对应有值,依次执行里面的方法
this._events[type].forEach(fn=>fn())
}
};
module.exports = EventEmitter