EventBus 功能
const event = new EventBus()
function fn1(a, b) { console.log('fn1', a, b) }
function fn2(a, b) { console.log('fn2', a, b) }
function fn3(a, b) { console.log('fn3', a, b) }
event.on('key1', fn1)
event.on('key1', fn2)
event.once('key1', fn3)
event.on('xxxxxx', fn3)
event.emit('key1', 10, 20) // 触发 fn1 fn2 fn3
event.off('key1', fn1)
event.emit('key1', 100, 200) // 触发 fn2
分析
on 和 once 注册函数,存储起来
emit 时找到的对应的函数,执行
off 找到对应的函数,从对象中删除
注意区分 on 和 once
on 绑定的事件可以连续执行,除非 off
once 绑定的函数 emit 一次即删除,也可以未执行而被 off
数据结构上标识出 on 和 once
1
/**
* @description Event Bus
*/
export default class EventBus {
/**
* {
* 'key1': [
* { fn: fn1, isOnce: false },
* { fn: fn2, isOnce: false },