47 lines
873 B
Go
47 lines
873 B
Go
|
package zntg
|
||
|
|
||
|
type EventFn func()
|
||
|
|
||
|
type EventStateFn func(interface{})
|
||
|
|
||
|
func NewEvents() *Events {
|
||
|
return &Events{events: map[uint]EventStateFn{}}
|
||
|
}
|
||
|
|
||
|
type Events struct {
|
||
|
nextID uint
|
||
|
events map[uint]EventStateFn
|
||
|
}
|
||
|
|
||
|
type EventHandler interface {
|
||
|
AddHandler(EventStateFn) uint
|
||
|
AddHandlerEmpty(EventFn) uint
|
||
|
RemoveHandler(uint)
|
||
|
}
|
||
|
|
||
|
func (e *Events) Notify(state interface{}) bool {
|
||
|
if e.events == nil {
|
||
|
return false
|
||
|
}
|
||
|
for _, handler := range e.events {
|
||
|
handler(state)
|
||
|
}
|
||
|
return len(e.events) > 0
|
||
|
}
|
||
|
|
||
|
func (e *Events) AddHandler(handler EventStateFn) uint {
|
||
|
if e.events == nil {
|
||
|
e.events = map[uint]EventStateFn{}
|
||
|
}
|
||
|
id := e.nextID
|
||
|
e.nextID++
|
||
|
e.events[id] = handler
|
||
|
return id
|
||
|
}
|
||
|
|
||
|
func (e *Events) AddHandlerEmpty(handler EventFn) uint {
|
||
|
return e.AddHandler(func(interface{}) { handler() })
|
||
|
}
|
||
|
|
||
|
func (e *Events) RemoveHandler(id uint) { delete(e.events, id) }
|