EventEmitter.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* eslint-disable
  2. camelcase,
  3. max-len,
  4. no-return-assign,
  5. no-unused-vars,
  6. */
  7. // TODO: This file was created by bulk-decaffeinate.
  8. // Fix any style issues and re-enable lint.
  9. /*
  10. * decaffeinate suggestions:
  11. * DS101: Remove unnecessary use of Array.from
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS207: Consider shorter variations of null checks
  14. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  15. */
  16. define([], function() {
  17. // Simple event emitter implementation, but has a slightly unusual API for
  18. // removing specific listeners. If a specific listener needs to be removed
  19. // (instead of all listeners), then it needs to use a "namespace":
  20. // Create a listener on the foo event with bar namespace: .on 'foo.bar'
  21. // Trigger all events for the foo event (including namespaces): .trigger 'foo'
  22. // Remove all listeners for the foo event (including namespaces): .off 'foo'
  23. // Remove a listener for the foo event with the bar namespace: .off 'foo.bar'
  24. let EventEmitter
  25. return (EventEmitter = class EventEmitter {
  26. on(event, callback) {
  27. let namespace
  28. if (!this.events) {
  29. this.events = {}
  30. }
  31. ;[event, namespace] = Array.from(event.split('.'))
  32. if (!this.events[event]) {
  33. this.events[event] = []
  34. }
  35. return this.events[event].push({
  36. callback,
  37. namespace
  38. })
  39. }
  40. off(event) {
  41. if (!this.events) {
  42. this.events = {}
  43. }
  44. if (event != null) {
  45. let namespace
  46. ;[event, namespace] = Array.from(event.split('.'))
  47. if (namespace == null) {
  48. // Clear all listeners for event
  49. return delete this.events[event]
  50. } else {
  51. // Clear only namespaced listeners
  52. const remaining_events = []
  53. for (let callback of Array.from(this.events[event] || [])) {
  54. if (callback.namespace !== namespace) {
  55. remaining_events.push(callback)
  56. }
  57. }
  58. return (this.events[event] = remaining_events)
  59. }
  60. } else {
  61. // Remove all listeners
  62. return (this.events = {})
  63. }
  64. }
  65. trigger(event, ...args) {
  66. if (!this.events) {
  67. this.events = {}
  68. }
  69. return Array.from(this.events[event] || []).map(callback =>
  70. callback.callback(...Array.from(args || []))
  71. )
  72. }
  73. emit(...args) {
  74. return this.trigger(...Array.from(args || []))
  75. }
  76. })
  77. })