bus.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package event
  2. // Should be called manager?
  3. // Bus can be implemente in other structs
  4. type Bus interface {
  5. Emitter
  6. Receiver
  7. }
  8. // EventBus implementation
  9. type eventBus struct {
  10. system *System
  11. handlers map[string]*[]HandlerFunc
  12. }
  13. // NewBus Creates and Initializes an eventBus
  14. /*func NewBus() Bus {
  15. return &eventBus{handlers: map[string]*[]HandlerFunc{}}
  16. }*/
  17. func (e *eventBus) handleEvent(evt Event) {
  18. handlerList, ok := e.handlers[evt.Name()]
  19. if !ok {
  20. return
  21. }
  22. for _, handler := range *handlerList {
  23. handler(evt)
  24. }
  25. // Special case
  26. catchList, ok := e.handlers["*"]
  27. if !ok {
  28. return
  29. }
  30. for _, handler := range *catchList {
  31. handler(evt)
  32. }
  33. }
  34. // This should send to system
  35. func (e *eventBus) Emit(evt Event) {
  36. e.system.handleEvent(evt) // Forward to system
  37. }
  38. // Register locally
  39. func (e *eventBus) On(name string, handler HandlerFunc) {
  40. handlerList, ok := e.handlers[name]
  41. if !ok {
  42. handlerList = &[]HandlerFunc{}
  43. e.handlers[name] = handlerList
  44. }
  45. *handlerList = append(*handlerList, handler)
  46. }