util.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.EventBus = exports.throttle = exports.formatSeconds = void 0;
  4. function formatSeconds(seconds) {
  5. var result = typeof seconds === "string" ? parseFloat(seconds) : seconds;
  6. if (isNaN(result))
  7. return "";
  8. let h = Math.floor(result / 3600) < 10
  9. ? "0" + Math.floor(result / 3600)
  10. : Math.floor(result / 3600);
  11. let m = Math.floor((result / 60) % 60) < 10
  12. ? "0" + Math.floor((result / 60) % 60)
  13. : Math.floor((result / 60) % 60) + h * 60;
  14. let s = Math.floor(result % 60) < 10
  15. ? "0" + Math.floor(result % 60)
  16. : Math.floor(result % 60);
  17. return `${m}:${s}`;
  18. }
  19. exports.formatSeconds = formatSeconds;
  20. function throttle(fn, wait) {
  21. let previous = 0;
  22. return function (...arg) {
  23. let context = this;
  24. let now = Date.now();
  25. //每隔一段时间执行一次;
  26. if (now - previous > wait) {
  27. fn.apply(context, arg);
  28. previous = now;
  29. }
  30. };
  31. }
  32. exports.throttle = throttle;
  33. class EventBus {
  34. constructor() {
  35. this._events = new Map();
  36. }
  37. on(event, action, fn) {
  38. let arr = this._events.get(event);
  39. let hasAction = arr
  40. ? arr.findIndex((i) => i.action == action)
  41. : -1;
  42. if (hasAction > -1) {
  43. return;
  44. }
  45. this._events.set(event, [
  46. ...(this._events.get(event) || []),
  47. {
  48. action,
  49. fn,
  50. },
  51. ]);
  52. }
  53. has(event) {
  54. return this._events.has(event);
  55. }
  56. emit(event, data) {
  57. if (!this.has(event)) {
  58. return;
  59. }
  60. let arr = this._events.get(event);
  61. arr.forEach((i) => {
  62. i.fn(data);
  63. });
  64. }
  65. off(event, action) {
  66. if (!this.has(event)) {
  67. return;
  68. }
  69. let arr = this._events.get(event);
  70. let newdata = arr.filter((i) => i.action !== action);
  71. this._events.set(event, [...newdata]);
  72. }
  73. }
  74. exports.EventBus = EventBus;