1. 1 : /**
  2. 2 : * An Object that contains lifecycle hooks as keys which point to an array
  3. 3 : * of functions that are run when a lifecycle is triggered
  4. 4 : *
  5. 5 : * @private
  6. 6 : */
  7. 7 : const hooks_ = {};
  8. 8 :
  9. 9 : /**
  10. 10 : * Get a list of hooks for a specific lifecycle
  11. 11 : *
  12. 12 : * @param {string} type
  13. 13 : * the lifecyle to get hooks from
  14. 14 : *
  15. 15 : * @param {Function|Function[]} [fn]
  16. 16 : * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  17. 17 : *
  18. 18 : * @return {Array}
  19. 19 : * an array of hooks, or an empty array if there are none.
  20. 20 : */
  21. 21 : const hooks = function(type, fn) {
  22. 22 : hooks_[type] = hooks_[type] || [];
  23. 23 : if (fn) {
  24. 24 : hooks_[type] = hooks_[type].concat(fn);
  25. 25 : }
  26. 26 : return hooks_[type];
  27. 27 : };
  28. 28 :
  29. 29 : /**
  30. 30 : * Add a function hook to a specific videojs lifecycle.
  31. 31 : *
  32. 32 : * @param {string} type
  33. 33 : * the lifecycle to hook the function to.
  34. 34 : *
  35. 35 : * @param {Function|Function[]}
  36. 36 : * The function or array of functions to attach.
  37. 37 : */
  38. 38 : const hook = function(type, fn) {
  39. 39 : hooks(type, fn);
  40. 40 : };
  41. 41 :
  42. 42 : /**
  43. 43 : * Remove a hook from a specific videojs lifecycle.
  44. 44 : *
  45. 45 : * @param {string} type
  46. 46 : * the lifecycle that the function hooked to
  47. 47 : *
  48. 48 : * @param {Function} fn
  49. 49 : * The hooked function to remove
  50. 50 : *
  51. 51 : * @return {boolean}
  52. 52 : * The function that was removed or undef
  53. 53 : */
  54. 54 : const removeHook = function(type, fn) {
  55. 55 : const index = hooks(type).indexOf(fn);
  56. 56 :
  57. 57 : if (index <= -1) {
  58. 58 : return false;
  59. 59 : }
  60. 60 :
  61. 61 : hooks_[type] = hooks_[type].slice();
  62. 62 : hooks_[type].splice(index, 1);
  63. 63 :
  64. 64 : return true;
  65. 65 : };
  66. 66 :
  67. 67 : /**
  68. 68 : * Add a function hook that will only run once to a specific videojs lifecycle.
  69. 69 : *
  70. 70 : * @param {string} type
  71. 71 : * the lifecycle to hook the function to.
  72. 72 : *
  73. 73 : * @param {Function|Function[]}
  74. 74 : * The function or array of functions to attach.
  75. 75 : */
  76. 76 : const hookOnce = function(type, fn) {
  77. 77 : hooks(type, [].concat(fn).map(original => {
  78. 78 : const wrapper = (...args) => {
  79. 79 : removeHook(type, wrapper);
  80. 80 : return original(...args);
  81. 81 : };
  82. 82 :
  83. 83 : return wrapper;
  84. 84 : }));
  85. 85 : };
  86. 86 :
  87. 87 : export {
  88. 88 : hooks_,
  89. 89 : hooks,
  90. 90 : hook,
  91. 91 : hookOnce,
  92. 92 : removeHook
  93. 93 : };