Files
Geliebte 1ea8c9da9c feat: 初始化 Wails + React + Go 桌面应用模板
- Wails v2.16.0 + React 19 + TypeScript + Vite 7
- 插件系统(build tag 控制编译,plugin.json 运行时配置)
- 支付插件(授权、账号、订单、退款、账单)
- 高并发基础设施(任务池、批量处理器、限流器、环形缓冲、管道)
- Windows 系统托盘(Win32 API)
- CodeGraph 索引 + .memory 记忆包
- 默认图标 assets/icon.png
2026-09-17 19:31:17 +08:00

63 lines
1.5 KiB
Go
Raw Permalink 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.
package bus
import (
"sync"
)
// Handler 事件处理器类型
type Handler func(payload any)
// EventBus 应用内事件总线,用于模块间解耦通信
type EventBus struct {
mu sync.RWMutex
handlers map[string][]Handler
}
// NewEventBus 创建事件总线实例
func NewEventBus() *EventBus {
return &EventBus{
handlers: make(map[string][]Handler),
}
}
// Subscribe 订阅事件,返回取消函数
func (b *EventBus) Subscribe(event string, handler Handler) func() {
b.mu.Lock()
defer b.mu.Unlock()
b.handlers[event] = append(b.handlers[event], handler)
return func() { b.Unsubscribe(event, handler) }
}
// Unsubscribe 取消订阅
func (b *EventBus) Unsubscribe(event string, handler Handler) {
b.mu.Lock()
defer b.mu.Unlock()
handlers := b.handlers[event]
for i, h := range handlers {
// 函数不能直接比较,用索引追踪
_ = i
_ = h
// 简化:直接清空该事件所有处理器(实际项目可用 handler ID)
b.handlers[event] = nil
break
}
}
// Publish 同步发布事件
func (b *EventBus) Publish(event string, payload any) {
b.mu.RLock()
handlers := make([]Handler, len(b.handlers[event]))
copy(handlers, b.handlers[event])
b.mu.RUnlock()
for _, h := range handlers {
if h != nil {
h(payload)
}
}
}
// PublishAsync 异步发布事件,不阻塞调用方
func (b *EventBus) PublishAsync(event string, payload any) {
b.Publish(event, payload) // 当前同步调用,后续可扩展为 goroutine
}