Last active
May 6, 2023 17:36
-
-
Save rbrahul/22a87f83ca47ec3d0e0aa09ea9ad5e7a to your computer and use it in GitHub Desktop.
Custom event handling in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
type EventType interface { | |
AddEventListener(string, func(interface{})) | |
Trigger(string, interface{}) | |
} | |
type CustomEvent struct { | |
listeners map[string][]func(interface{}) | |
} | |
var event EventType | |
func NewCustomEvent() EventType { | |
if event == nil { | |
event = &CustomEvent{listeners: map[string][]func(interface{}){}} | |
} | |
return event | |
} | |
func (ce *CustomEvent) AddEventListener(eventType string, hanlder func(interface{})) { | |
if hanlders, ok := ce.listeners[eventType]; !ok { | |
ce.listeners[eventType] = []func(interface{}){hanlder} | |
} else { | |
ce.listeners[eventType] = append(hanlders, hanlder) | |
} | |
} | |
func (ce *CustomEvent) Trigger(eventType string, data interface{}) { | |
if hanlders, ok := ce.listeners[eventType]; ok { | |
for _, handler := range hanlders { | |
handler(data) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/rbrahul/eventhandler" // tried in locally with go mod replace. didn't publish to github | |
) | |
func main() { | |
var myCustomEvent EventType = NewCustomEvent() | |
myCustomEvent.AddEventListener("send_email", func(data interface{}) { | |
fmt.Printf("Verifying email adress:%v before sending\n", data) | |
}) | |
myCustomEvent.AddEventListener("send_email", func(data interface{}) { | |
fmt.Println("Sending mail to:", data) | |
}) | |
fmt.Println("Going to trigger send_mail") | |
time.Sleep(2 * time.Second) | |
myCustomEvent.Trigger("send_email", "[email protected]") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment