goemitter/main.go

99 lines
2.2 KiB
Go
Raw Normal View History

2023-11-29 23:48:57 +08:00
// Package goemitter
package goemitter
import (
"sync"
)
type EventEmitter struct {
2024-11-16 16:12:20 +08:00
callbacks map[string]map[int]func(args ...interface{})
2023-11-29 23:48:57 +08:00
onceCallbacks map[string][]func(args ...interface{})
lock sync.Mutex
2024-11-16 16:12:20 +08:00
counter int
2023-11-29 23:48:57 +08:00
}
2024-11-16 16:12:20 +08:00
type EventHandle struct {
id int
event string
emitter *EventEmitter
}
func (eh *EventHandle) Remove() {
eh.emitter.lock.Lock()
defer eh.emitter.lock.Unlock()
if _, ok := eh.emitter.callbacks[eh.event]; ok {
delete(eh.emitter.callbacks[eh.event], eh.id)
}
}
func (e *EventEmitter) On(event string, callback func(args ...interface{})) *EventHandle {
2023-11-29 23:48:57 +08:00
e.lock.Lock()
defer e.lock.Unlock()
2024-11-16 16:12:20 +08:00
e.counter++
2023-11-29 23:48:57 +08:00
if _, ok := e.callbacks[event]; !ok {
2024-11-16 16:12:20 +08:00
e.callbacks[event] = make(map[int]func(args ...interface{}))
}
e.callbacks[event][e.counter] = callback
return &EventHandle{
id: e.counter,
event: event,
emitter: e,
2023-11-29 23:48:57 +08:00
}
}
func (e *EventEmitter) Once(event string, callback func(args ...interface{})) {
e.lock.Lock()
defer e.lock.Unlock()
if _, ok := e.onceCallbacks[event]; !ok {
2024-09-19 16:19:02 +08:00
e.onceCallbacks[event] = []func(args ...interface{}){callback}
} else {
2023-11-29 23:48:57 +08:00
e.onceCallbacks[event] = append(e.onceCallbacks[event], callback)
}
}
func (e *EventEmitter) Emit(event string, data ...interface{}) {
e.lock.Lock()
defer e.lock.Unlock()
if callbacks, ok := e.callbacks[event]; ok {
for _, callback := range callbacks {
go callback(data...)
}
}
if onceCallbacks, ok := e.onceCallbacks[event]; ok {
for _, callback := range onceCallbacks {
go callback(data...)
}
e.onceCallbacks[event] = []func(args ...interface{}){}
}
}
func (e *EventEmitter) EmitSync(event string, data ...interface{}) {
e.lock.Lock()
defer e.lock.Unlock()
if callbacks, ok := e.callbacks[event]; ok {
for _, callback := range callbacks {
callback(data...)
}
}
if onceCallbacks, ok := e.onceCallbacks[event]; ok {
for _, callback := range onceCallbacks {
callback(data...)
}
e.onceCallbacks[event] = []func(args ...interface{}){}
}
}
func NewEmitter() *EventEmitter {
ret := &EventEmitter{}
2024-11-16 16:12:20 +08:00
ret.callbacks = make(map[string]map[int]func(args ...interface{}))
2023-11-29 23:48:57 +08:00
ret.onceCallbacks = make(map[string][]func(args ...interface{}))
return ret
}