mirror of
https://github.com/issadarkthing/gomu.git
synced 2025-04-30 13:48:50 +08:00
add EventHook
This commit is contained in:
parent
dcce622458
commit
310a43f8cf
31
hook/hook.go
Normal file
31
hook/hook.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package hook
|
||||||
|
|
||||||
|
type EventHook struct {
|
||||||
|
events map[string][]func()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEventHook() EventHook {
|
||||||
|
return EventHook{make(map[string][]func())}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EventHook) AddHook(eventName string, handler func()) {
|
||||||
|
|
||||||
|
hooks, ok := e.events[eventName]
|
||||||
|
if !ok {
|
||||||
|
e.events[eventName] = []func(){handler}
|
||||||
|
}
|
||||||
|
|
||||||
|
e.events[eventName] = append(hooks, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EventHook) RunHooks(eventName string) {
|
||||||
|
|
||||||
|
hooks, ok := e.events[eventName]
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, hook := range hooks {
|
||||||
|
hook()
|
||||||
|
}
|
||||||
|
}
|
31
hook/hook_test.go
Normal file
31
hook/hook_test.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package hook
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRunHook(t *testing.T) {
|
||||||
|
|
||||||
|
h := NewEventHook()
|
||||||
|
i := 0
|
||||||
|
|
||||||
|
h.AddHook("sample", func() {
|
||||||
|
i++
|
||||||
|
})
|
||||||
|
|
||||||
|
h.AddHook("sample", func() {
|
||||||
|
i++
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.Equal(t, i, 0)
|
||||||
|
|
||||||
|
h.RunHooks("x")
|
||||||
|
|
||||||
|
assert.Equal(t, i, 0)
|
||||||
|
|
||||||
|
h.RunHooks("sample")
|
||||||
|
|
||||||
|
assert.Equal(t, i, 2)
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user