55 lines
834 B
Go
55 lines
834 B
Go
|
package events
|
||
|
|
||
|
import (
|
||
|
"sync"
|
||
|
)
|
||
|
|
||
|
type eventHandler func(args ...interface{})
|
||
|
|
||
|
var (
|
||
|
eventMap = make(map[string][]eventHandler)
|
||
|
eventMapLock sync.RWMutex
|
||
|
|
||
|
allListeners = make([]eventHandler, 0)
|
||
|
|
||
|
initialized = false
|
||
|
)
|
||
|
|
||
|
func On(name string, f eventHandler) {
|
||
|
eventMapLock.Lock()
|
||
|
defer eventMapLock.Unlock()
|
||
|
|
||
|
handlers, exists := eventMap[name]
|
||
|
|
||
|
if !exists {
|
||
|
handlers = make([]eventHandler, 0)
|
||
|
}
|
||
|
|
||
|
handlers = append(handlers, f)
|
||
|
|
||
|
eventMap[name] = handlers
|
||
|
}
|
||
|
|
||
|
func OnALl(f eventHandler) {
|
||
|
allListeners = append(allListeners, f)
|
||
|
}
|
||
|
|
||
|
func Call(name string, args ...interface{}) {
|
||
|
if !initialized && name != Init {
|
||
|
Call(Init)
|
||
|
initialized = true
|
||
|
}
|
||
|
|
||
|
eventMapLock.RLock()
|
||
|
handlers, exists := eventMap[name]
|
||
|
eventMapLock.RUnlock()
|
||
|
|
||
|
if !exists {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
for _, handler := range handlers {
|
||
|
handler(args...)
|
||
|
}
|
||
|
}
|