-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatcher.go
96 lines (75 loc) · 2.12 KB
/
dispatcher.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
92
93
94
95
96
package event
import "sync"
type Dispatcher interface {
Register(eventType string, handler Handler)
AddListener(eventType string, listener *Listener)
RemoveListener(eventType string, listener *Listener) bool
HasListener(eventType string) bool
DispatchEvent(event Event) bool
Trigger(eventType string, params interface{}) bool
}
type eventDispatcher struct {
savers map[string]*Saver
sync.RWMutex
}
func NewDispatcher() Dispatcher {
return &eventDispatcher{savers: make(map[string]*Saver)}
}
func (dispatcher *eventDispatcher) Register(eventType string, handler Handler) {
dispatcher.AddListener(eventType, NewListener(handler))
}
func (dispatcher *eventDispatcher) AddListener(eventType string, listener *Listener) {
dispatcher.Lock()
defer dispatcher.Unlock()
saver, ok := dispatcher.savers[eventType]
if !ok {
saver = &Saver{Type: eventType, Listeners: []*Listener{listener}}
dispatcher.savers[eventType] = saver
return
}
saver.Lock()
defer saver.Unlock()
saver.Listeners = append(saver.Listeners, listener)
}
func (dispatcher *eventDispatcher) RemoveListener(eventType string, listener *Listener) bool {
dispatcher.Lock()
defer dispatcher.Unlock()
saver, ok := dispatcher.savers[eventType]
if !ok {
return false
}
saver.Lock()
defer saver.Unlock()
for i, l := range saver.Listeners {
if l == listener {
saver.Listeners = append(saver.Listeners[:i], saver.Listeners[i+1:]...)
return true
}
}
return false
}
func (dispatcher *eventDispatcher) HasListener(eventType string) bool {
dispatcher.RLock()
defer dispatcher.RUnlock()
_, ok := dispatcher.savers[eventType]
return ok
}
func (dispatcher *eventDispatcher) DispatchEvent(event Event) bool {
dispatcher.RLock()
defer dispatcher.RUnlock()
saver, ok := dispatcher.savers[event.TypeName()]
if !ok {
return false
}
saver.RLock()
defer saver.RUnlock()
for _, listener := range saver.Listeners {
event.SetDispatcher(dispatcher)
go listener.Handler(event)
}
return true
}
func (dispatcher *eventDispatcher) Trigger(eventType string, params interface{}) bool {
event := NewEvent(eventType, params)
return dispatcher.DispatchEvent(event)
}