EventEmitter.coffee 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. define [], () ->
  2. # Simple event emitter implementation, but has a slightly unusual API for
  3. # removing specific listeners. If a specific listener needs to be removed
  4. # (instead of all listeners), then it needs to use a "namespace":
  5. # Create a listener on the foo event with bar namespace: .on 'foo.bar'
  6. # Trigger all events for the foo event (including namespaces): .trigger 'foo'
  7. # Remove all listeners for the foo event (including namespaces): .off 'foo'
  8. # Remove a listener for the foo event with the bar namespace: .off 'foo.bar'
  9. class EventEmitter
  10. on: (event, callback) ->
  11. @events ||= {}
  12. [event, namespace] = event.split(".")
  13. @events[event] ||= []
  14. @events[event].push {
  15. callback: callback
  16. namespace: namespace
  17. }
  18. off: (event) ->
  19. @events ||= {}
  20. if event?
  21. [event, namespace] = event.split(".")
  22. if !namespace?
  23. # Clear all listeners for event
  24. delete @events[event]
  25. else
  26. # Clear only namespaced listeners
  27. remaining_events = []
  28. for callback in @events[event] or []
  29. if callback.namespace != namespace
  30. remaining_events.push callback
  31. @events[event] = remaining_events
  32. else
  33. # Remove all listeners
  34. @events = {}
  35. trigger: (event, args...) ->
  36. @events ||= {}
  37. for callback in @events[event] or []
  38. callback.callback(args...)
  39. emit: (args...) -> @trigger(args...)