events.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS101: Remove unnecessary use of Array.from
  6. * DS102: Remove unnecessary code created because of implicit returns
  7. * DS104: Avoid inline assignments
  8. * DS207: Consider shorter variations of null checks
  9. * DS208: Avoid top-level this
  10. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
  11. */
  12. class Events {
  13. on(event, callback) {
  14. if (event.indexOf(" ") >= 0) {
  15. for (var name of Array.from(event.split(" "))) {
  16. this.on(name, callback);
  17. }
  18. } else {
  19. let base;
  20. ((base =
  21. this._callbacks != null ? this._callbacks : (this._callbacks = {}))[
  22. event
  23. ] != null
  24. ? base[event]
  25. : (base[event] = [])
  26. ).push(callback);
  27. }
  28. return this;
  29. }
  30. off(event, callback) {
  31. let callbacks, index;
  32. if (event.indexOf(" ") >= 0) {
  33. for (var name of Array.from(event.split(" "))) {
  34. this.off(name, callback);
  35. }
  36. } else if (
  37. (callbacks =
  38. this._callbacks != null ? this._callbacks[event] : undefined) &&
  39. (index = callbacks.indexOf(callback)) >= 0
  40. ) {
  41. callbacks.splice(index, 1);
  42. if (!callbacks.length) {
  43. delete this._callbacks[event];
  44. }
  45. }
  46. return this;
  47. }
  48. trigger(event, ...args) {
  49. this.eventInProgress = { name: event, args };
  50. const callbacks = this._callbacks?.[event];
  51. if (callbacks) {
  52. for (let callback of Array.from(callbacks.slice(0))) {
  53. if (typeof callback === "function") {
  54. callback(...args);
  55. }
  56. }
  57. }
  58. this.eventInProgress = null;
  59. if (event !== "all") {
  60. this.trigger("all", event, ...Array.from(args));
  61. }
  62. return this;
  63. }
  64. removeEvent(event) {
  65. if (this._callbacks != null) {
  66. for (var name of Array.from(event.split(" "))) {
  67. delete this._callbacks[name];
  68. }
  69. }
  70. return this;
  71. }
  72. }