daily pastebin goal
44%
SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "reflect"
  6.     "time"
  7. )
  8.  
  9. type EventHandler struct {
  10.     listeners []func(...interface{})
  11. }
  12.  
  13. func (eh *EventHandler) AddListener(action func(...interface{})) {
  14.     eh.listeners = append(eh.listeners, action)
  15. }
  16.  
  17. func (eh *EventHandler) RemoveListener(action func(...interface{})) {
  18.     for i, listener := range eh.listeners {
  19.         if reflect.ValueOf(listener) == reflect.ValueOf(action) {
  20.             eh.listeners = append(eh.listeners[:i], eh.listeners[i+1:]...)
  21.             return
  22.         }
  23.     }
  24. }
  25.  
  26. func (eh *EventHandler) Clear() {
  27.     eh.listeners = eh.listeners[:0]
  28. }
  29.  
  30. func (eh *EventHandler) Invoke(params ...interface{}) {
  31.     for _, listener := range eh.listeners {
  32.         listener(params...)
  33.     }
  34. }
  35.  
  36. type TestListener struct {
  37.     name   string
  38.     action func(...interface{})
  39. }
  40.  
  41. func (tl *TestListener) Foo() func(...interface{}) {
  42.     return func(params ...interface{}) {
  43.         fmt.Printf("%s Trigger !!! %v\n", tl.name, params)
  44.     }
  45. }
  46.  
  47. func (tl *TestListener) Bar() func(...interface{}) {
  48.     return func(params ...interface{}) {
  49.         fmt.Printf("%s Trigger !!! %v\n", tl.name, params)
  50.     }
  51. }
  52.  
  53. var onDoSomething EventHandler = EventHandler{}
  54.  
  55. func main() {
  56.     test1 := TestListener{}
  57.     test1.name = "Test01"
  58.     test1.action = test1.Foo()
  59.  
  60.     test2 := TestListener{}
  61.     test2.name = "Test02"
  62.     test2.action = test2.Foo()
  63.  
  64.     onDoSomething.AddListener(test1.action)
  65.     onDoSomething.AddListener(test2.action)
  66.  
  67.     fmt.Println("Start counting ...")
  68.     time.Sleep(time.Duration(2) * time.Second)
  69.     onDoSomething.Invoke("Hello Mars")
  70.  
  71.     fmt.Println("\nRemove Listener 2 ...")
  72.     onDoSomething.RemoveListener(test2.action)
  73.     onDoSomething.RemoveListener(test2.action)
  74.     time.Sleep(time.Duration(2) * time.Second)
  75.     onDoSomething.Invoke(1, 2, 3, 4)
  76.  
  77.     fmt.Println("\nClear Listener ...")
  78.     onDoSomething.Clear()
  79.     fmt.Println("Add Listenter 2 again...")
  80.     onDoSomething.AddListener(test2.action)
  81.     time.Sleep(time.Duration(2) * time.Second)
  82.     onDoSomething.Invoke("GGEz")
  83. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top