手写EventBus自定义事件
Posted 沿着路走到底
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写EventBus自定义事件相关的知识,希望对你有一定的参考价值。
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 ,
以上是关于手写EventBus自定义事件的主要内容,如果未能解决你的问题,请参考以下文章