API
Since: 1.3.3
After
In many situations, it's important to ensure that the frontend API has been fully initialized, especially when you intend to make use of hyvaCheckout sub-namespaces, such as when registering a custom validator.
The after method either waits until the checkout API is fully initialised, or dispatches the callback immediately if that has already occurred.
Use the checkout:init:after window event when you simply want to execute code independently of any result and with the certainty that everything belonging to the API has run.
Parameters:
callback(callable, required) - The callback that needs to be executed as soon as the API is initialized.options(object, optional)stackPosition(int, optional) -500by default
Returns:
void- No return value
<script>
(() => {
const options = {
// Set the execution order; run before validators with a higher stackPosition (default is 500 if not specified)
stackPosition: 400
};
const callback = () => {
// Register a custom validator. Note: developers are responsible for handling any validation errors ourselves.
hyvaCheckout.validation.register('sensible-validation-name', async () => {
// Simulate an API call or async operation with a 2-second delay.
await new Promise(resolve => setTimeout(resolve, 2000));
// Simulate the (random) return of either true or false.
const valid = Math.random() < 0.5;
// When creating a validator, error handling is the developer's responsibility,
// allowing full control over how to notify the customer of a failed validation.
if (valid === false) {
console.log('Validation failed – error handling must be implemented manually.');
}
// Should always return true or false.
return valid;
});
};
// Ensure the frontend API is fully initialized before registering the custom validation logic.
hyvaCheckout.api.after(callback, options)
// Chain additional functionality to run after the validator has been successfully registered.
.then(() => console.log('Validator registration complete – you can sit back and relax.'));
})();
</script>
Some values are assigned to const variables for improved readability, although they can obviously be passed in directly as a method argument.
Priority (since 1.3.4)
Should only be used for core contributions; included here for awareness reasoning.
The priority method allows core systems to run earlier than those that should run after. This method is a wrapper for the after method, automatically applying a stackPosition of 20 whilst still allowing things to run before this if genuinely needed.
However, we cannot currently think of any situation where priorities earlier than 20 should be set, meaning such priorities should never be used.