-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
83 lines (73 loc) · 1.62 KB
/
event.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
package wechat
import (
"fmt"
"reflect"
)
const (
messagePrefix = "msg"
eventPrefix = "event"
)
type Handler func(msg MessageReceive) MessageReply
type Ev struct {
subscribers map[string][]Handler
}
func newEv() *Ev {
return &Ev{
subscribers: make(map[string][]Handler, 0),
}
}
func (e *Ev) get(event string) []Handler {
return e.subscribers[event]
}
func (e *Ev) trigger(msg *MessageReceive) []Handler {
ret := make([]Handler, 0)
if msg.MsgType == "" {
return ret
}
if msg.IsEvent() {
if msg.Event != "" {
if msg.EventKey != "" {
if es := e.get(fmt.Sprintf("%s.%s.%s", msg.MsgType, msg.Event, msg.EventKey)); es != nil {
ret = append(ret, es...)
}
}
if es := e.get(fmt.Sprintf("%s.%s", msg.MsgType, msg.Event)); es != nil {
ret = append(ret, es...)
}
}
if es := e.get(eventPrefix); es != nil {
ret = append(ret, es...)
}
} else {
if es := e.get(fmt.Sprintf("%s.%s", messagePrefix, msg.MsgType)); es != nil {
ret = append(ret, es...)
}
if es := e.get(messagePrefix); es != nil {
ret = append(ret, es...)
}
}
return ret
}
//添加订阅
func (e *Ev) On(event string, handler Handler) Unsubscribe {
e.subscribers[event] = append(e.subscribers[event], handler)
return func() {
e.Off(event, handler)
}
}
type Unsubscribe func()
//取消订阅
func (e *Ev) Off(event string, handler Handler) {
handlers, ok := e.subscribers[event]
if !ok {
//do nothing
return
}
newHandlers := make([]Handler, 0)
for _, h := range handlers {
if reflect.ValueOf(h) != reflect.ValueOf(handler) {
newHandlers = append(newHandlers, h)
}
}
e.subscribers[event] = newHandlers
}