1.发布 - 订阅 - 事件中心
class EventEmit {
constructor() {
// 事件中心
this.eventMap = {}
}
// 订阅事件
on(type, handler) {
if (!(handler instanceof Function)) {
// 传入的必须是一个函数
throw new Error('必须是一个函数')
}
if (!this.eventMap[type]) {
// 如果不存在设置为一个空数组
this.eventMap[type] = []
}
// 将回调函数添加到实践中心
this.eventMap[type].push(handler)
}
// 发布事件
emit(type, params) {
if (this.eventMap[type]) {
// 依次执行订阅的事件
this.eventMap[type].forEach(handler => handler(params))
}
}
// 移除事件
off(type, handler) {
if (this.eventMap[type]) {
// 移除指定的事件 >>> 符号 好好理解一下
// indexOf在-1的情况下,splice会把数组中的最后一项给删除了
// 使用 >>> 无符号右移 后 -1 会变成 32位全是 1的 二进制数
this.eventMap[type].splice(this.eventMap[type].indexOf(handler) >>> 0, 1)
}
}
}
2.测试
const ee = new EventEmit()
const handler1 = params => {
console.log('第一次订阅', params)
}
const handler2 = params => {
console.log('第二次订阅', params)
}
ee.on('tt', handler1)
ee.on('tt', handler2)
ee.emit('tt', '发布事件')
ee.off('tt', handler2)
ee.emit('tt', '发布事件')
// 打印如下
第一次订阅 发布事件
第二次订阅 发布事件
第一次订阅 发布事件