-
Notifications
You must be signed in to change notification settings - Fork 11
/
observable.go
85 lines (67 loc) · 1.91 KB
/
observable.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
package observable
import (
"reflect"
"sync"
)
// event key uset to listen and remove all the events
const ALL_EVENTS_NAMESPACE = "*"
// Structs
// private struct
type callback struct {
fn reflect.Value
isUnique bool
isTyped bool
wasCalled bool
}
// Public Observable struct
type Observable struct {
Callbacks map[string][]callback
*sync.RWMutex
}
// Public API
// New - returns a new observable reference
func New() *Observable {
return &Observable{
make(map[string][]callback),
&sync.RWMutex{},
}
}
// On - adds a callback function
func (o *Observable) On(event string, cb interface{}) *Observable {
return o.addCallback(event, cb, false)
}
// Trigger - a particular event passing custom arguments
func (o *Observable) Trigger(event string, params ...interface{}) *Observable {
// get the arguments we want to pass to our listeners callbaks
arguments := make([]reflect.Value, len(params))
// get all the arguments
for i, param := range params {
arguments[i] = reflect.ValueOf(param)
}
o.dispatchEvent(event, arguments)
// trigger the all events callback whenever this event was defined
if o.hasEvent(ALL_EVENTS_NAMESPACE) && event != ALL_EVENTS_NAMESPACE {
o.dispatchEvent(ALL_EVENTS_NAMESPACE, append([]reflect.Value{reflect.ValueOf(event)}, arguments...))
}
return o
}
// Off - stop listening a particular event
func (o *Observable) Off(event string, args ...interface{}) *Observable {
if len(args) == 0 {
// wipe all the event listeners
if event == ALL_EVENTS_NAMESPACE {
o.Lock()
o.Callbacks = make(map[string][]callback)
o.Unlock()
}
} else if len(args) == 1 {
o.removeEvent(event, args[0])
} else {
panic("Multiple off callbacks are not supported")
}
return o
}
// One - call the callback only once
func (o *Observable) One(event string, cb interface{}) *Observable {
return o.addCallback(event, cb, true)
}