当前位置: 首页 > news >正文

前端小技巧: TS实现EventBus自定义事件

关于EventBus事件总线

  • 事件总线,实现 on, once, emit, off
    • on, once 是注册函数,存储起来
    • emit时找到对应的函数,执行
    • off找到对应的函数,从对象中删除
  • 注意
    • 区分on和once
    • on绑定的事件可连续执行,除非off
    • once绑定的函数 emit 一次即删除,也可未执行而被 off
    • 数据结构上标识出 on 和 once

实现方案1

代码实现:使用参数区分 on和once

class EventBus {/*{key1: [{fn: fn1, isOnce: false},{fn: fn2, isOnce: false},{fn: fn3, isOnce: true},],key2: []}*/private events: {[key: string]: Array<{fn: Function; isOnce: boolean}>}constructor() {this.events = {};}on(type: string, fn: Function, isOnce: boolean = false) {const events = this.events;if (events[type] == null) {events[type] = []; // 初始化 key 的 fn 数组}events[type].push({fn, isOnce});},// 这里是初步版本once_origin(type: string, fn: Function) {const events = this.events;if (events[type] == null) {events[type] = []; // 初始化 key 的 fn 数组}events[type].push({fn, isOnce: true});},once(type: string, fn: Function, isOnce: boolean = false) {this.on(type, fn, true);},off(type: string, fn?:Function) {if (!fn) {// 解绑所有 type 的函数this.events[type] = [];} else {// 解绑单个 fnconst fnList = this.events[type];if (fnList.length) {this.events[type] = fnList.filter(item.fn !== fn);}}},emit(type: string, ...args: any[]) {const fnList = this.events[type];if (fnList == null) return;// 注意this.events[type] = fnList.filter(item => {const { fn, isOnce } = item;fn(...args);// 处理once, 它执行一次就要被过滤掉if (!isOnce) return true;return false;})}
}const e = new EventBus();
function fn1(a: any, b: any) {console.log('fn1', a, b)};
function fn2(a: any, b: any) {console.log('fn2', a, b)};
function fn3(a: any, b: any) {console.log('fn3', a, b)};e.on('key1', fn1);
e.on('key1', fn2);
e.once('key1', fn3);e.emit('key1', 10, 20); // 触发 fn1, fn2, fn3
e.off('key1', fn1);
e.emit('key1', 100, 200); // 触发 fn2

实现方案2

代码实现: 拆分保存 on和once

class EventBus {private events: { [key: string]: Array<Function>} // {key1: [fn1, fn2]}private onceEvents: {[key: string]: Array<Function>} // 结构同上constructor() {this.events = {}; // 存储 onthis.onceEvents = {}; // 存储 once}// on 触发on(type: string, fn: Function) {const events = this.events;if (events[type] === null) events[type] = [];events[type].push(fn);},once(type: string, fn: Function) {const onceEvents = this.onceEvents;if (onceEvents[type] === null) onceEvents[type] = [];onceEvents[type].push(fn);},// 解绑事件off(type: string, fn: Function) {if (!fn) {// 解绑所有事件this.events[type] = [];this.onceEvents[type] = [];} else {// 解绑单个const fnList = this.events[type];const onceFnList = this.onceEvents[type];if (fnList.length) {this.events[type] = fnList.filter(curFn => curFN!== fn);}if (onceFnList.length) {this.onceEvents[type] = onceFnList.filter(curFn => curFN!== fn);}}},emit(type: string, ...args: any[]) {const fnList = this.events[type];const onceFnList = this.onceEvents[type];if (fnList.length) {fnList.forEach(f => f(...args));}if (onceFnList.length) {onceFnList.forEach(f => f(...args));// once 执行一次就删除,这里更简单,代码更简洁this.onceEvents[type] = [];}}
}// 测试用例同上,此处省略

总结

  • 区分 on, once
  • 合理的数据结构,比算法优化更有效
http://www.lryc.cn/news/225993.html

相关文章:

  • Django之三板斧的使用,全局配置文件介绍,request对象方法,pycharm链接数据库,Django链接数据库,ORM的增删改查
  • 医学影像系统源码(MRI、CT三维重建)
  • 【uniapp】仿微信通讯录列表实现
  • [MT8766][Android12] 增加应用安装白名单或者黑名单
  • 游戏公司数据分析师必备知识(持续补充中...)
  • intellj 开发软件插件
  • leetCode 493 翻转对
  • “辛巴猫舍”内网渗透、提权、撞库学习笔记
  • 粤嵌实训医疗项目--day06(Vue + SpringBoot)
  • SPSS二元Logistic回归
  • 前端-第一部分-HTML
  • 六度空间(C++)
  • 记录undefined reference to `SSLv3_client_method‘错误笔记
  • JS算法练习 11.11
  • 50代码审计-PHP无框架项目SQL注入挖掘
  • 什么是微服务?与分布式又有什么区别?
  • 案例 | 3D可视化工具HOOPS助力SolidWorks edrawings成功引入AR/VR技术
  • 初识Linux:目录路径
  • 抖音小程序开发:探索技术创新的代码之旅
  • 公司注册股东选择几个人合适?
  • 大数据治理——为业务提供持续的、可度量的价值(二)
  • 前端安全方面有哪些攻击方式?
  • linux的文件属性
  • 电脑指示灯闪烁,但是无法开机的解决方案
  • 【电工基础】
  • 【Word自定义配置,超简单,图文并茂】自定义Word中的默认配置,比如标题大小与颜色(参考科研作图配色),正文字体等
  • 常见排序算法之快速排序
  • ESP32 C3 smartconfig一键配网报错
  • 力扣labuladong——一刷day25
  • 从单体到微服务:使用Spring Boot构建事件驱动的Java应用程序