Files
zmkgC/third/plane/event/event.go
2025-07-07 20:11:59 +08:00

89 lines
2.2 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 event
// eventHandlerInfo定义了事件处理器的信息
type eventHandlerInfo struct {
handler EventHandler // 事件处理函数
once bool // 是否只执行一次
}
// EventHandler定义了事件处理函数的类型
type EventHandler func(params ...any)
// Event表示一个事件对象
type Event struct {
handlers []eventHandlerInfo // 事件处理器列表
}
// Attach将事件处理器附加到事件对象中并返回处理器在列表中的索引
func (e *Event) Attach(handler EventHandler) int {
handlerInfo := eventHandlerInfo{handler, true} //默认只执行一次
for i, h := range e.handlers {
if h.handler == nil {
e.handlers[i] = handlerInfo
return i
}
}
e.handlers = append(e.handlers, handlerInfo)
return len(e.handlers) - 1
}
// Detach从事件对象中移除指定索引处的处理器
func (e *Event) Detach(handle int) {
e.handlers[handle].handler = nil
}
// Once将事件处理器附加到事件对象中并将处理器标记为只执行一次
func (e *Event) Once(handler EventHandler) {
i := e.Attach(handler)
e.handlers[i].once = true
}
// EventPublisher表示事件发布者
type EventPublisher struct {
event Event // 事件对象
}
// Event返回事件对象的指针
func (p *EventPublisher) Event() *Event {
return &p.event
}
// Publish触发事件依次执行事件对象中的处理器并在处理器标记为只执行一次时将其从事件对象中移除
func (p *EventPublisher) Publish(params ...any) {
for i, h := range p.event.handlers {
if h.handler != nil {
h.handler(params...)
if h.once {
p.event.Detach(i)
}
}
}
}
func GetEvent(fn func(params ...any)) *EventPublisher {
publisher := &EventPublisher{}
// 定义一个事件处理器函数
handler := fn
// 将事件处理器附加到事件列表中
publisher.Event().Attach(handler)
return publisher
}
/*func main() {
// 在这里编写您的代码逻辑
// 创建一个事件发布者
publisher := &EventPublisher{}
// 定义一个事件处理器函数
handler := func() {
fmt.Println("Event handled!")
}
// 将事件处理器附加到事件列表中
publisher.Event().Attach(handler)
// 发布事件
publisher.Publish()
}*/