goevent is an event emitter similar to javascript's custom events.
Note :
This is not a pattern you should have inside your code all over the place . You should use this package for specific use cases. Some of those use cases are listed below.
Use Case :
- Init / Shutdown events for your rest api
- Async Processing
- PUB->SUB Local events
- etc ...
go get github.com/baderkha/goevent
This section will cover exemplar scenarios for this package. This package can be used to emit global events you can subscribe to anywhere in the code , or local events if you want to manage / orchestrate the events.
For Global Events you first need to init the global emitter as such
-
Init
// somewhere in your main func func main() { // IF YOU DO NOT DO THIS , THIS WILL CRASH // choose to have your panics handled gracefully handlePanics := true goevent.InitGlobal(handlePanics) }
-
Add Event Listener
// somewhere else listenerHash := goevent. Global(). AddListener("slim_shady", func(d interface{}) { name := d.(string) fmt.Println("BAND NAME => " + name) })
-
Emit Event
// somewhere else goevent. Global(). Emit("slim_shady","d12") // with the event emitted above this will output // "BAND NAME => d12"
-
Remove Event Listener
// somewhere else hasBeenRemoved := goevent. Global(). RemoveListener(listenerHash) // will be false if it doesn't exist fmt.Println(hasBeenRemoved)
For Local events you can construct them from any where and attach them to structs
-
Init
// from anywhere handlePanics := true // choose to have your panics handled // this object is local ie everytime you call new you get a new one ev := goevent.New(handlePanics)
-
Add Event Listener
listenerHash:= ev.AddListener("slim_shady", func(d interface{}) { name := d.(string) fmt.Println("BAND NAME => " + name) })
-
Emit Event
ev.Emit("slim_shady","d12")
-
Remove Event Listener
ev.RemoveListener(listenerHash)