Posted 2018-09-25Updated 2020-11-24前端2 minutes read (About 282 words)EventBus-javascript事件总线1. class实现1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162class EventBus { handlers: any = {}; /** * 发布事件 * @param type {String} 事件名 * @param params 参数 */ emit(type: string, ...params: any) { // 若没有注册该事件则抛出错误 if (!(type in this.handlers)) { return new Error('未注册该事件') } // 便利触发 this.handlers[type].forEach((handler: Function) => { handler(...params) }) } /** * 订阅事件 * @param type {String} 事件名 * @param handler {Function} 事件方法 */ addEventListener (type: string, handler: any) { // 首先判断handlers内有没有type事件容器,没有则创建一个新数组容器 if (!(type in this.handlers)) { this.handlers[type] = [] } // 将事件存入 this.handlers[type].push(handler) } /** * 取消订阅 * @param type {String} 事件名 * @param handler 删除的事件,若无该参数则删除该事件的订阅和发布 */ removeEventListener (type: string, handler: any) { // 无效事件抛出 if (!(type in this.handlers)) { return new Error('无效事件') } if (!handler) { // 直接移除事件 delete this.handlers[type] } else { const idx = this.handlers[type].findIndex((ele: any) => ele === handler) // 抛出异常事件 if (idx === undefined) { return new Error('无该绑定事件') } // 移除事件 this.handlers[type].splice(idx, 1) if (this.handlers[type].length === 0) { delete this.handlers[type] } } }}export default new EventBus(); 2.基于node模块实现1234567const EventEmitter = require('events');const evtBus = new EventEmitter();evtBus.setMaxListeners(20);evtBus.on('error', (err) => { console.error(err, 'error');});export default evtBus;