forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
49 lines (44 loc) · 840 Bytes
/
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
package gobot
type callback struct {
f func(interface{})
once bool
}
type Event struct {
Chan chan interface{}
Callbacks []callback
}
// NewEvent generates a new event by making a channel
// and start reading from it
func NewEvent() *Event {
e := &Event{
Chan: make(chan interface{}, 1),
Callbacks: []callback{},
}
go func() {
for {
e.Read()
}
}()
return e
}
// Writes sends event data to channel
func (e *Event) Write(data interface{}) {
select {
case e.Chan <- data:
default:
}
}
// Read waits data from channel and execute callbacks
// for each event when received
func (e *Event) Read() {
for s := range e.Chan {
tmp := []callback{}
for i := range e.Callbacks {
go e.Callbacks[i].f(s)
if !e.Callbacks[i].once {
tmp = append(tmp, e.Callbacks[i])
}
}
e.Callbacks = tmp
}
}