Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "reflect"
- "time"
- )
- type EventHandler struct {
- listeners []func(...interface{})
- }
- func (eh *EventHandler) AddListener(action func(...interface{})) {
- eh.listeners = append(eh.listeners, action)
- }
- func (eh *EventHandler) RemoveListener(action func(...interface{})) {
- for i, listener := range eh.listeners {
- if reflect.ValueOf(listener) == reflect.ValueOf(action) {
- eh.listeners = append(eh.listeners[:i], eh.listeners[i+1:]...)
- return
- }
- }
- }
- func (eh *EventHandler) Clear() {
- eh.listeners = eh.listeners[:0]
- }
- func (eh *EventHandler) Invoke(params ...interface{}) {
- for _, listener := range eh.listeners {
- listener(params...)
- }
- }
- type TestListener struct {
- name string
- action func(...interface{})
- }
- func (tl *TestListener) Foo() func(...interface{}) {
- return func(params ...interface{}) {
- fmt.Printf("%s Trigger !!! %v\n", tl.name, params)
- }
- }
- func (tl *TestListener) Bar() func(...interface{}) {
- return func(params ...interface{}) {
- fmt.Printf("%s Trigger !!! %v\n", tl.name, params)
- }
- }
- var onDoSomething EventHandler = EventHandler{}
- func main() {
- test1 := TestListener{}
- test1.name = "Test01"
- test1.action = test1.Foo()
- test2 := TestListener{}
- test2.name = "Test02"
- test2.action = test2.Foo()
- onDoSomething.AddListener(test1.action)
- onDoSomething.AddListener(test2.action)
- fmt.Println("Start counting ...")
- time.Sleep(time.Duration(2) * time.Second)
- onDoSomething.Invoke("Hello Mars")
- fmt.Println("\nRemove Listener 2 ...")
- onDoSomething.RemoveListener(test2.action)
- onDoSomething.RemoveListener(test2.action)
- time.Sleep(time.Duration(2) * time.Second)
- onDoSomething.Invoke(1, 2, 3, 4)
- fmt.Println("\nClear Listener ...")
- onDoSomething.Clear()
- fmt.Println("Add Listenter 2 again...")
- onDoSomething.AddListener(test2.action)
- time.Sleep(time.Duration(2) * time.Second)
- onDoSomething.Invoke("GGEz")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement