1*740e3947S猫头猫import EventEmitter from 'eventemitter3'; 2*740e3947S猫头猫 3*740e3947S猫头猫class EventBus<EventTypes> { 4*740e3947S猫头猫 private ee: EventEmitter; 5*740e3947S猫头猫 6*740e3947S猫头猫 constructor() { 7*740e3947S猫头猫 this.ee = new EventEmitter(); 8*740e3947S猫头猫 } 9*740e3947S猫头猫 10*740e3947S猫头猫 /** 11*740e3947S猫头猫 * 监听 12*740e3947S猫头猫 * @param eventName 事件名 13*740e3947S猫头猫 * @param callBack 回调 14*740e3947S猫头猫 */ 15*740e3947S猫头猫 on<T extends EventTypes, K extends keyof T & (string | symbol)>( 16*740e3947S猫头猫 eventName: K, 17*740e3947S猫头猫 callBack: (payload: T[K]) => void, 18*740e3947S猫头猫 ) { 19*740e3947S猫头猫 this.ee.on(eventName, callBack); 20*740e3947S猫头猫 } 21*740e3947S猫头猫 22*740e3947S猫头猫 once<T extends EventTypes, K extends keyof T & (string | symbol)>( 23*740e3947S猫头猫 eventName: K, 24*740e3947S猫头猫 callBack: (payload: T[K]) => void, 25*740e3947S猫头猫 ) { 26*740e3947S猫头猫 this.ee.once(eventName, callBack); 27*740e3947S猫头猫 } 28*740e3947S猫头猫 29*740e3947S猫头猫 emit<T extends EventTypes, K extends keyof T & (string | symbol)>( 30*740e3947S猫头猫 eventName: K, 31*740e3947S猫头猫 payload?: T[K], 32*740e3947S猫头猫 ) { 33*740e3947S猫头猫 this.ee.emit(eventName, payload); 34*740e3947S猫头猫 } 35*740e3947S猫头猫 36*740e3947S猫头猫 off<T extends EventTypes, K extends keyof T & (string | symbol)>( 37*740e3947S猫头猫 eventName: K, 38*740e3947S猫头猫 callBack: (payload: T[K]) => void, 39*740e3947S猫头猫 ) { 40*740e3947S猫头猫 this.ee.off(eventName, callBack); 41*740e3947S猫头猫 } 42*740e3947S猫头猫} 43*740e3947S猫头猫 44*740e3947S猫头猫export default EventBus; 45