2025-05-22 20:42:10 +08:00

79 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 事件总线类型定义
type EventCallback = (...args: any[]) => void
// 事件总线实现
class EventBus {
private events: Record<string, EventCallback[]> = {}
// 订阅事件
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,
})
}