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