-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomevent.go
91 lines (73 loc) · 1.49 KB
/
customevent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package engine
import (
"strings"
"github.com/blackprint/engine-go/utils"
)
type eventObj struct {
callback any
once bool
}
type CustomEvent struct {
events map[string][]*eventObj
}
func (e *CustomEvent) listen(evName string, callback any, once bool) {
if e.events == nil {
e.events = map[string][]*eventObj{}
}
evs := strings.Split(evName, " ")
for _, name := range evs {
list := e.events[name]
// Only add when not exist
exist := false
for _, cb := range list {
if cb.callback == callback {
exist = true
break
}
}
if exist {
continue
}
e.events[name] = append(list, &eventObj{
callback: callback,
once: once,
})
}
}
func (e *CustomEvent) On(evName string, callback any) {
e.listen(evName, callback, false)
}
func (e *CustomEvent) Once(evName string, callback any) {
e.listen(evName, callback, true)
}
func (e *CustomEvent) Off(evName string, callback any) {
if e.events == nil {
return
}
evs := strings.Split(evName, " ")
for _, name := range evs {
if callback == nil {
e.events[name] = []*eventObj{}
continue
}
list := e.events[name]
if list == nil {
continue
}
for i, cb := range list {
if cb.callback == callback {
e.events[name] = utils.RemoveItemAtIndex(list, i)
continue
}
}
}
}
func (e *CustomEvent) Emit(evName string, data any) {
list := e.events[evName]
for i, cb := range list {
cb.callback.(func(any))(data)
if cb.once {
e.events[evName] = utils.RemoveItemAtIndex(list, i)
}
}
}