12345678910111213141516171819202122 |
- // event-bus.js
- const EventBus = {
- events: {} as any,
- // 重新定义的 on 方法,用于注册事件监听器,现在同一个 eventName 只会保留最后注册的那个监听器
- on: function (eventName: string, callback: Function) {
- this.events[eventName] = callback;
- },
- // 用于触发事件,通知注册的监听器执行相应逻辑
- emit: function (eventName: string, data: any) {
- if (this.events[eventName]) {
- this.events[eventName](data);
- }
- },
- // 新增的关闭事件方法,用于移除指定事件的监听器
- off: function (eventName: string) {
- if (this.events[eventName]) {
- delete this.events[eventName];
- }
- }
- };
- export default EventBus;
|