-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.go
50 lines (41 loc) · 1.13 KB
/
dispatcher.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
package events
type ListenerContract interface {
Handle(event string, args ...interface{}) error
}
type DispatcherContract interface {
/**
* Register an event listener with the dispatcher.
*/
Listen(event string, listener ListenerContract)
/**
* Dispatch an event and call the listeners.
*/
Dispatch(event string, args ...interface{}) error
}
type Dispatcher struct {
listeners map[string][]ListenerContract
}
func New() *Dispatcher {
listeners := make(map[string][]ListenerContract)
return &Dispatcher{
listeners: listeners,
}
}
// Register an event listener with the dispatcher.
func (dispatcher *Dispatcher) Listen(event string, listeners []ListenerContract) {
for _, listener := range listeners { //nolint:gosimple
dispatcher.listeners[event] = append(dispatcher.listeners[event], listener)
}
}
// Dispatch an event and call the listeners.
func (dispatcher *Dispatcher) Dispatch(event string, args ...interface{}) error {
if listeners, ok := dispatcher.listeners[event]; ok {
for _, listener := range listeners {
err := listener.Handle(event, args...)
if err != nil {
return err
}
}
}
return nil
}