event-bus.ts 726 B

12345678910111213141516171819202122
  1. // event-bus.js
  2. const EventBus = {
  3. events: {} as any,
  4. // 重新定义的 on 方法,用于注册事件监听器,现在同一个 eventName 只会保留最后注册的那个监听器
  5. on: function (eventName: string, callback: Function) {
  6. this.events[eventName] = callback;
  7. },
  8. // 用于触发事件,通知注册的监听器执行相应逻辑
  9. emit: function (eventName: string, data: any) {
  10. if (this.events[eventName]) {
  11. this.events[eventName](data);
  12. }
  13. },
  14. // 新增的关闭事件方法,用于移除指定事件的监听器
  15. off: function (eventName: string) {
  16. if (this.events[eventName]) {
  17. delete this.events[eventName];
  18. }
  19. }
  20. };
  21. export default EventBus;