EventEmitter.js 2.5 KB

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