You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6 KiB

  1. export default {
  2. readyStates: [],
  3. callbacks: [],
  4. /**
  5. * Check if event has been sent
  6. *
  7. * @param {String} evt Event name
  8. * @returns {Boolean} True if fired
  9. */
  10. isReady (evt) {
  11. return this.readyStates.indexOf(evt) >= 0
  12. },
  13. /**
  14. * Register a callback to be executed when event is sent
  15. *
  16. * @param {String} evt Event name to register to
  17. * @param {Function} clb Callback function
  18. * @param {Boolean} once If the callback should be called only once
  19. */
  20. register (evt, clb, once) {
  21. if (this.isReady(evt)) {
  22. clb()
  23. } else {
  24. this.callbacks.push({
  25. event: evt,
  26. callback: clb,
  27. once: false,
  28. called: false
  29. })
  30. }
  31. },
  32. /**
  33. * Register a callback to be executed only once when event is sent
  34. *
  35. * @param {String} evt Event name to register to
  36. * @param {Function} clb Callback function
  37. */
  38. registerOnce (evt, clb) {
  39. this.register(evt, clb, true)
  40. },
  41. /**
  42. * Set ready state and execute callbacks
  43. */
  44. notify (evt) {
  45. this.readyStates.push(evt)
  46. this.callbacks.forEach(clb => {
  47. if (clb.event === evt) {
  48. if (clb.once && clb.called) {
  49. return
  50. }
  51. clb.called = true
  52. clb.callback()
  53. }
  54. })
  55. },
  56. /**
  57. * Execute callback on DOM ready
  58. *
  59. * @param {Function} clb Callback function
  60. */
  61. onDOMReady (clb) {
  62. if (document.readyState === 'interactive' || document.readyState === 'complete' || document.readyState === 'loaded') {
  63. clb()
  64. } else {
  65. document.addEventListener('DOMContentLoaded', clb)
  66. }
  67. }
  68. }