2020-05-16 07:36:04 +00:00
|
|
|
package zntg
|
|
|
|
|
2020-05-16 10:07:13 +00:00
|
|
|
type EventEmptyFn func()
|
2020-05-16 07:36:04 +00:00
|
|
|
|
2020-05-16 10:07:13 +00:00
|
|
|
type EventFn func(interface{})
|
2020-05-16 07:36:04 +00:00
|
|
|
|
|
|
|
func NewEvents() *Events {
|
2020-05-16 10:07:13 +00:00
|
|
|
return &Events{events: map[uint]EventFn{}}
|
2020-05-16 07:36:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Events struct {
|
|
|
|
nextID uint
|
2020-05-16 10:07:13 +00:00
|
|
|
events map[uint]EventFn
|
2020-05-16 07:36:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type EventHandler interface {
|
2020-05-16 10:07:13 +00:00
|
|
|
AddHandler(EventFn) uint
|
|
|
|
AddHandlerEmpty(EventEmptyFn) uint
|
2020-05-16 07:36:04 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-05-16 10:07:13 +00:00
|
|
|
func (e *Events) AddHandler(handler EventFn) uint {
|
2020-05-16 07:36:04 +00:00
|
|
|
if e.events == nil {
|
2020-05-16 10:07:13 +00:00
|
|
|
e.events = map[uint]EventFn{}
|
2020-05-16 07:36:04 +00:00
|
|
|
}
|
|
|
|
id := e.nextID
|
|
|
|
e.nextID++
|
|
|
|
e.events[id] = handler
|
|
|
|
return id
|
|
|
|
}
|
|
|
|
|
2020-05-16 10:07:13 +00:00
|
|
|
func (e *Events) AddHandlerEmpty(handler EventEmptyFn) uint {
|
2020-05-16 07:36:04 +00:00
|
|
|
return e.AddHandler(func(interface{}) { handler() })
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Events) RemoveHandler(id uint) { delete(e.events, id) }
|