bus.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. emitPrefix string
  12. handlers map[string]*[]HandlerFunc
  13. }
  14. // NewBus Creates and Initializes an eventBus
  15. /*func NewBus() Bus {
  16. return &eventBus{handlers: map[string]*[]HandlerFunc{}}
  17. }*/
  18. func (e *eventBus) handleEvent(evt Event) {
  19. handlerList, ok := e.handlers[evt.Name()]
  20. if !ok {
  21. return
  22. }
  23. for _, handler := range *handlerList {
  24. handler(evt)
  25. }
  26. // Special case
  27. catchList, ok := e.handlers["*"]
  28. if !ok {
  29. return
  30. }
  31. for _, handler := range *catchList {
  32. handler(evt)
  33. }
  34. }
  35. // This should send to system
  36. func (e *eventBus) Emit(name string, data interface{}) {
  37. var evt Event
  38. if e.emitPrefix != "" {
  39. evt = New(e.emitPrefix+namedPrefixer+name, data)
  40. } else {
  41. evt = New(name, data)
  42. }
  43. e.system.handleEvent(evt) // Forward to system
  44. }
  45. // Register locally
  46. func (e *eventBus) On(name string, handler HandlerFunc) {
  47. handlerList, ok := e.handlers[name]
  48. if !ok {
  49. handlerList = &[]HandlerFunc{}
  50. e.handlers[name] = handlerList
  51. }
  52. *handlerList = append(*handlerList, handler)
  53. }