Skip to content

Instantly share code, notes, and snippets.

@arikw
Created July 24, 2023 19:10
Show Gist options
  • Save arikw/fcf641dc56872862dec2aede0ef3cb68 to your computer and use it in GitHub Desktop.
Save arikw/fcf641dc56872862dec2aede0ef3cb68 to your computer and use it in GitHub Desktop.
A helper utility for triggering a callback when events will be triggered or were already triggered
/**
* Triggers a callback function when all the specified events are validated as completed.
* @param {Object[]} eventsWithValidators - An array of objects containing the event name, event target and status checker function for each event.
* @param {string} eventsWithValidators[].eventName - The name of the event to listen for.
* @param {EventTarget} [eventsWithValidators[].eventTarget=window] - The object that emits the event. If not specified, window will be used as the default event target.
* @param {Function} eventsWithValidators[].statusChecker - A function that returns a boolean value indicating whether the event is completed or not.
* @param {Function} callback - The function to execute when all the events are completed.
* @example
* runWhenEventsCompleted([
{ eventName: 'load', statusChecker: () => document.readyState === 'complete' },
{ eventName: 'nuxt-loaded', statusChecker: () => window.isNuxtLoaded }
], () => console.log('completed!'));
*/
export function runWhenEventsCompleted(eventsWithValidators, callback) {
/**
* Checks if all the events are completed and triggers the callback if so.
* Otherwise, adds an event listener for each event that is not completed yet.
*/
function checkAllCompleted() {
for (const { eventName, eventTarget, statusChecker } of eventsWithValidators) {
if (!statusChecker()) {
(eventTarget || window).addEventListener(eventName, checkAllCompleted, { once: true });
return;
}
}
callback();
}
checkAllCompleted();
}
/**
* Triggers a callback function when the specified event is validated as completed.
* @param {Object} eventWithValidator - An object containing the event name, event target and status checker function for the event.
* @param {string} eventWithValidator.eventName - The name of the event to listen for.
* @param {EventTarget} [eventWithValidator.eventTarget=window] - The object that emits the event. If not specified, window will be used as the default event target.
* @param {Function} eventWithValidator.statusChecker - A function that returns a boolean value indicating whether the event is completed or not.
* @param {Function} callback - The function to execute when the event is completed.
* @example
* runWhenEventCompleted(
{ eventName: 'load', statusChecker: () => document.readyState === 'complete' },
() => console.log('completed!')
);
*/
export function runWhenEventCompleted(eventWithValidator, callback) {
return runWhenEventsCompleted([ eventWithValidator ], callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment