-
Notifications
You must be signed in to change notification settings - Fork 43
/
ebus.go
53 lines (41 loc) · 1.05 KB
/
ebus.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
package ebus
import (
"container/list"
"github.com/ivpusic/golog"
)
var log = golog.GetLogger("github.com/ivpusic/neo")
// Handler for event
type EvHandler func(interface{})
// Map with name of event and list of listeners.
type events map[string]list.List
type EBus struct {
eventList events
}
func (b *EBus) InitEBus() {
b.eventList = events{}
}
// Registering listener for provided event.
func (e *EBus) On(event string, fn EvHandler) {
log.Debugf("registering event `%s`", event)
topic, ok := e.eventList[event]
if !ok {
topic = list.List{}
}
topic.PushBack(fn)
e.eventList[event] = topic
}
// Emitting event with data. One goroutine per emit will be created.
func (e *EBus) Emit(event string, data interface{}) {
go func() {
log.Debugf("emmiting event `%s`", event)
if topic, ok := e.eventList[event]; ok {
log.Debug("found listeners for event " + event)
for el := topic.Front(); el != nil; el = el.Next() {
fn := el.Value.(EvHandler)
fn(data)
}
} else {
log.Debugf("listeners for event %s not found", event)
}
}()
}