gomu/hook/hook.go

36 lines
703 B
Go
Raw Normal View History

2021-02-19 10:25:34 +08:00
package hook
type EventHook struct {
events map[string][]func()
}
2021-02-19 22:22:24 +08:00
// NewNewEventHook returns new instance of EventHook
2021-02-19 12:08:56 +08:00
func NewEventHook() *EventHook {
return &EventHook{make(map[string][]func())}
2021-02-19 10:25:34 +08:00
}
2021-02-19 22:22:24 +08:00
// AddHook accepts a function which will be executed when the event is emitted.
2021-02-19 10:25:34 +08:00
func (e *EventHook) AddHook(eventName string, handler func()) {
hooks, ok := e.events[eventName]
if !ok {
e.events[eventName] = []func(){handler}
2021-02-19 12:08:56 +08:00
return
2021-02-19 10:25:34 +08:00
}
e.events[eventName] = append(hooks, handler)
}
2021-02-19 22:22:24 +08:00
// RunHooks executes all hooks installed for an event.
2021-02-19 10:25:34 +08:00
func (e *EventHook) RunHooks(eventName string) {
hooks, ok := e.events[eventName]
if !ok {
return
}
for _, hook := range hooks {
hook()
}
}