事件发布订阅模式简单实现:
实现思路:
- 声明一个类 EventEmitter
- 添加私有属性this.db对象,用来保存事件
- emit() 方法,用来发布事件
- on() 方法,用来订阅事件
- once() 方法,用来订阅事件并且只执行一次事件回调,然后就销毁
- off() 方法,用来注销某种类型事件的某个回调(一种类型的事件一般都有多处订阅,所以有多个回调)
具体代码实现:
export class EventEmitter {
constructor() {
this.db = Object.create(null)
}
emit(type, payload) {
const handlers = (this.db[type] || []).slice()
if (handlers && handlers.length) {
handlers.forEach(handler => handler(payload))
}
}
on(type, handler) {
if (!this.db[type]) {
this.db[type] = []
}
this.db[type].push(handler)
return this
}
once(type, handler) {
const emiter = this
function on() {
emiter.off(type, on)
handler.apply(emiter, arguments)
}
emiter.on(type, on)
}
off(type, handler) {
const handlers = this.db[type]
if (handlers) {
for (let i = 0; i < handlers.length; ++i) {
if (handlers[i] === handler) {
handlers.splice(i, 1)
break
}
}
}
}
}
export const eventEmitter = new EventEmitter()