event_dispatcher.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package raft
  2. import (
  3. "reflect"
  4. "sync"
  5. )
  6. // eventDispatcher is responsible for managing listeners for named events
  7. // and dispatching event notifications to those listeners.
  8. type eventDispatcher struct {
  9. sync.RWMutex
  10. source interface{}
  11. listeners map[string]eventListeners
  12. }
  13. // EventListener is a function that can receive event notifications.
  14. type EventListener func(Event)
  15. // EventListeners represents a collection of individual listeners.
  16. type eventListeners []EventListener
  17. // newEventDispatcher creates a new eventDispatcher instance.
  18. func newEventDispatcher(source interface{}) *eventDispatcher {
  19. return &eventDispatcher{
  20. source: source,
  21. listeners: make(map[string]eventListeners),
  22. }
  23. }
  24. // AddEventListener adds a listener function for a given event type.
  25. func (d *eventDispatcher) AddEventListener(typ string, listener EventListener) {
  26. d.Lock()
  27. defer d.Unlock()
  28. d.listeners[typ] = append(d.listeners[typ], listener)
  29. }
  30. // RemoveEventListener removes a listener function for a given event type.
  31. func (d *eventDispatcher) RemoveEventListener(typ string, listener EventListener) {
  32. d.Lock()
  33. defer d.Unlock()
  34. // Grab a reference to the function pointer once.
  35. ptr := reflect.ValueOf(listener).Pointer()
  36. // Find listener by pointer and remove it.
  37. listeners := d.listeners[typ]
  38. for i, l := range listeners {
  39. if reflect.ValueOf(l).Pointer() == ptr {
  40. d.listeners[typ] = append(listeners[:i], listeners[i+1:]...)
  41. }
  42. }
  43. }
  44. // DispatchEvent dispatches an event.
  45. func (d *eventDispatcher) DispatchEvent(e Event) {
  46. d.RLock()
  47. defer d.RUnlock()
  48. // Automatically set the event source.
  49. if e, ok := e.(*event); ok {
  50. e.source = d.source
  51. }
  52. // Dispatch the event to all listeners.
  53. for _, l := range d.listeners[e.Type()] {
  54. l(e)
  55. }
  56. }