EventEmitter.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // Simple event emitter implementation, but has a slightly unusual API for
  17. // removing specific listeners. If a specific listener needs to be removed
  18. // (instead of all listeners), then it needs to use a "namespace":
  19. // Create a listener on the foo event with bar namespace: .on 'foo.bar'
  20. // Trigger all events for the foo event (including namespaces): .trigger 'foo'
  21. // Remove all listeners for the foo event (including namespaces): .off 'foo'
  22. // Remove a listener for the foo event with the bar namespace: .off 'foo.bar'
  23. export default class EventEmitter {
  24. on(event, callback) {
  25. let namespace
  26. if (!this.events) {
  27. this.events = {}
  28. }
  29. ;[event, namespace] = Array.from(event.split('.'))
  30. if (!this.events[event]) {
  31. this.events[event] = []
  32. }
  33. return this.events[event].push({
  34. callback,
  35. namespace,
  36. })
  37. }
  38. off(event) {
  39. if (!this.events) {
  40. this.events = {}
  41. }
  42. if (event != null) {
  43. let namespace
  44. ;[event, namespace] = Array.from(event.split('.'))
  45. if (namespace == null) {
  46. // Clear all listeners for event
  47. return delete this.events[event]
  48. } else {
  49. // Clear only namespaced listeners
  50. const remaining_events = []
  51. for (const callback of Array.from(this.events[event] || [])) {
  52. if (callback.namespace !== namespace) {
  53. remaining_events.push(callback)
  54. }
  55. }
  56. return (this.events[event] = remaining_events)
  57. }
  58. } else {
  59. // Remove all listeners
  60. return (this.events = {})
  61. }
  62. }
  63. trigger(event, ...args) {
  64. if (!this.events) {
  65. this.events = {}
  66. }
  67. return Array.from(this.events[event] || []).map(callback =>
  68. callback.callback(...Array.from(args || []))
  69. )
  70. }
  71. emit(...args) {
  72. return this.trigger(...Array.from(args || []))
  73. }
  74. }