// 事件总线类型定义 type EventCallback = (...args: any[]) => void // 事件总线实现 class EventBus { private events: Record = {} // 订阅事件 on(event: string, callback: EventCallback): void { if (!this.events[event]) { this.events[event] = [] } this.events[event].push(callback) } // 取消订阅 off(event: string, callback?: EventCallback): void { if (!this.events[event]) return if (!callback) { delete this.events[event] } else { this.events[event] = this.events[event].filter((cb) => cb !== callback) } } // 触发事件 emit(event: string, ...args: any[]): void { if (!this.events[event]) return this.events[event].forEach((callback) => { callback(...args) }) } // 只订阅一次 once(event: string, callback: EventCallback): void { const onceCallback = (...args: any[]) => { callback(...args) this.off(event, onceCallback) } this.on(event, onceCallback) } } // 创建全局事件总线实例 export const eventBus = new EventBus() // 预定义事件类型 export const EVENT_TYPES = { API_ERROR: "api:error", NOTIFICATION: "notification", AUTH_EXPIRED: "auth:expired", } // 通知类型 export interface Notification { title: string message: string type: "success" | "error" | "warning" | "info" duration?: number } // 辅助函数:发送通知 export function notify(notification: Notification): void { eventBus.emit(EVENT_TYPES.NOTIFICATION, notification) } // 辅助函数:发送API错误通知 export function notifyApiError(title: string, message: string): void { notify({ title, message, type: "error", duration: 5000, }) }