Skip to main content

手写发布订阅

思路:数据结构 map={},三个方法

  1. 声明事件对象 map={}

  2. on 监听

    • map 中存在获取原数组 / 不存在则创建新数组
    • 把回调函数 fn 存入 map 事件数组
  3. emit 触发

    • 获取对应事件数组
    • 数组不存在则 return
    • 存在 map 遍历执行 fn
  4. off 取消

    • 获取对应事件数组
    • 数组不存在则 return
    • 函数不存在则 return
    • 存在 splice 删除
class EventHub {
map = {}
on(type,fn){
// key:存在就是原数组 / 不存在则创建新数组
this.map[type] = this.map[type] || []
// value
this.map[type].push(fn)
}
emit(type,args){
// 获取函数数组
const q = this.map[type]
// 是否数组为空
if(!q) return
// 执行函数数组
q.map(fn => fn.call(undefined,args))
}
off(type,fn){
// 获取函数数组
const q = this.map[type]
// 是否数组为空
if(!q) return
// 数组中对应函数是否存在
const index = q.indexOf(fn)
if(index < 0)return
// 删除:取消监听
q.splice(index,1)
}

}

使用方法:

// 使用
const e = new EventHub()

e.on('click', console.log)
e.on('click', console.error)

setTimeout(() => {
e.emit('click', 'frank')
}, 3000)

e.off('click', console.log)