-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
57 lines (46 loc) · 1.08 KB
/
utils.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
package govents
import (
"log"
"strings"
)
func listenTo[T comparable](eventEmitter *EventEmitter[T]) {
for {
func() {
// eventEmitter.eventsMu.Lock()
// defer eventEmitter.eventsMu.Unlock()
e, okay := <-eventEmitter.ch
if !okay {
log.Fatalln(ErrEventEmitterClosed)
}
event, ok := eventEmitter.events[e.eventName]
if !ok {
log.Fatalln(ErrNoEventFound(e.eventName))
}
if event.isOnce {
event.cb(e.cbFnArgs...)
delete(eventEmitter.events, e.eventName)
return
}
event.cb(e.cbFnArgs...)
}()
}
}
// to check for defaults and initialize an event
func initEvent[T comparable](e *EventEmitter[T], eventName string, cb Listener[T], isOnce bool) (event[T], error) {
eventName = strings.TrimSpace(eventName)
tempEvent := event[T]{
isOnce: isOnce,
cb: cb,
}
if _, eventExist := e.events[eventName]; eventExist {
return tempEvent, ErrDuplicateListeners
}
if eventName == "" {
return tempEvent, ErrNoEventName
}
if e.Len() >= e.maxEventListeners {
close(e.ch)
return tempEvent, ErrMaxListenerLimit
}
return tempEvent, nil
}