-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
93 lines (81 loc) · 2.1 KB
/
manager.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
package event
import (
"sort"
"sync"
)
//Manager is simple event manager
type Manager struct {
lock sync.Mutex
id uint32
events map[string]eventsStore
}
func (manager *Manager) listen(name string, fn func(interface{}) bool, order float32, once bool) (id uint32) {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.events[name] = append(manager.events[name], eventStore{
fn: fn,
order: order,
id: manager.id,
once: once,
})
id = manager.id
manager.id++
sort.Sort(manager.events[name])
return
}
//Subscribe listen to event
func (manager *Manager) Subscribe(name string, fn func(interface{}) bool, order float32) uint32 {
return manager.listen(name, fn, order, false)
}
//SubscribeOnce listen to event for once
func (manager *Manager) SubscribeOnce(name string, fn func(interface{}) bool, order float32) uint32 {
return manager.listen(name, fn, order, true)
}
//UnSubscribe remove listen to event
func (manager *Manager) UnSubscribe(name string, id uint32) {
manager.lock.Lock()
defer manager.lock.Unlock()
if events, ok := manager.events[name]; ok {
for index, event := range events {
if event.id == id {
manager.remove(name, index)
}
}
}
}
//UnSubscribeAll remove all listens to event
func (manager *Manager) UnSubscribeAll(name string) {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.events[name] = make(eventsStore, 0)
}
// Publish executes callback defined for event. if func return false stop execute and return false
func (manager *Manager) Publish(name string, arg interface{}) bool {
manager.lock.Lock()
defer manager.lock.Unlock()
if events, ok := manager.events[name]; ok {
for index, event := range events {
if event.once {
manager.remove(name, index)
}
if !event.fn(arg) {
return false
}
}
}
return true
}
func (manager *Manager) remove(name string, index int) {
if index >= 0 {
manager.events[name] = append(manager.events[name][:index],
manager.events[name][index+1:]...)
}
}
//NewManager retrun event manager
func NewManager() *Manager {
return &Manager{
sync.Mutex{},
0,
make(map[string]eventsStore),
}
}