bus.go 732 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package event
  2. // Should be called manager?
  3. // Bus can be implemente in other sturcts
  4. type Bus interface {
  5. Emitter
  6. Receiver
  7. }
  8. // EventBus implementation
  9. type eventBus struct {
  10. handlers map[string]*[]HandlerFunc
  11. }
  12. // NewBus Creates and Initializes an eventBus
  13. func NewBus() Bus {
  14. return &eventBus{handlers: map[string]*[]HandlerFunc{}}
  15. }
  16. func (e *eventBus) Emit(evt Event) {
  17. handlerList, ok := e.handlers[evt.Name()]
  18. if !ok {
  19. return
  20. }
  21. for _, handler := range *handlerList {
  22. handler(evt)
  23. }
  24. }
  25. func (e *eventBus) On(name string, handler HandlerFunc) {
  26. handlerList, ok := e.handlers[name]
  27. if !ok {
  28. handlerList = &[]HandlerFunc{}
  29. e.handlers[name] = handlerList
  30. }
  31. *handlerList = append(*handlerList, handler)
  32. }