events.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. class Events {
  2. on(event, callback) {
  3. if (event.includes(" ")) {
  4. for (var name of event.split(" ")) {
  5. this.on(name, callback);
  6. }
  7. } else {
  8. this._callbacks ||= {};
  9. this._callbacks[event] ||= [];
  10. this._callbacks[event].push(callback);
  11. }
  12. return this;
  13. }
  14. off(event, callback) {
  15. let callbacks, index;
  16. if (event.includes(" ")) {
  17. for (var name of event.split(" ")) {
  18. this.off(name, callback);
  19. }
  20. } else if (
  21. (callbacks = this._callbacks?.[event]) &&
  22. (index = callbacks.indexOf(callback)) >= 0
  23. ) {
  24. callbacks.splice(index, 1);
  25. if (!callbacks.length) {
  26. delete this._callbacks[event];
  27. }
  28. }
  29. return this;
  30. }
  31. trigger(event, ...args) {
  32. this.eventInProgress = { name: event, args };
  33. const callbacks = this._callbacks?.[event];
  34. if (callbacks) {
  35. for (let callback of callbacks.slice(0)) {
  36. if (typeof callback === "function") {
  37. callback(...args);
  38. }
  39. }
  40. }
  41. this.eventInProgress = null;
  42. if (event !== "all") {
  43. this.trigger("all", event, ...args);
  44. }
  45. return this;
  46. }
  47. removeEvent(event) {
  48. if (this._callbacks != null) {
  49. for (var name of event.split(" ")) {
  50. delete this._callbacks[name];
  51. }
  52. }
  53. return this;
  54. }
  55. }