github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/listener/listener.go (about) 1 package listener 2 3 type EventListener func(event BaseEvent) 4 5 var eventWatcherGroupMaps map[string]map[string][]EventListener 6 7 type BaseEvent interface { 8 Name() string 9 Group() string 10 } 11 12 func PublishEvent(event BaseEvent) { 13 if eventWatcherGroupMaps == nil { 14 return 15 } 16 if eventWatcherGroup, exist := eventWatcherGroupMaps[event.Group()]; exist { 17 if eventWatchers, exist := eventWatcherGroup[event.Name()]; exist { 18 for _, eventWatcher := range eventWatchers { 19 eventWatcher(event) 20 } 21 } 22 } 23 } 24 25 func AddListener(eventName string, eventListener EventListener) { 26 AddListenerWithGroup(DefaultGroup, eventName, eventListener) 27 } 28 29 func AddListenerWithGroup(group string, eventName string, eventListener EventListener) { 30 if eventWatcherGroupMaps == nil { 31 eventWatcherGroupMaps = map[string]map[string][]EventListener{} 32 } 33 34 if eventWatcherMap, exist := eventWatcherGroupMaps[group]; exist { 35 if eventWatchers, exist := eventWatcherMap[eventName]; exist { 36 eventWatchers = append(eventWatchers, eventListener) 37 eventWatcherMap[eventName] = eventWatchers 38 } else { 39 eventWatchers = []EventListener{} 40 eventWatchers = append(eventWatchers, eventListener) 41 eventWatcherMap[eventName] = eventWatchers 42 } 43 } else { 44 eventWatchers := []EventListener{} 45 eventWatchers = append(eventWatchers, eventListener) 46 47 eventMap := map[string][]EventListener{} 48 eventMap[eventName] = eventWatchers 49 eventWatcherGroupMaps[group] = eventMap 50 } 51 }