♻️ Extract button-refresh logic to own helper file

- Exrtract repeat event-init logic to new helper file
- Remove the jQuery dependency
This commit is contained in:
Philipp Stracker 2024-06-26 18:16:54 +02:00
parent 5ed2f37bd4
commit 4c10c37782
No known key found for this signature in database
4 changed files with 46 additions and 32 deletions

View file

@ -0,0 +1,37 @@
import { debounce } from '../../../../../ppcp-blocks/resources/js/Helper/debounce';
const REFRESH_BUTTON_EVENT = 'ppcp_refresh_payment_buttons';
/**
* Triggers a refresh of the payment buttons.
* This function dispatches a custom event that the button components listen for.
*
* Use this function on the front-end to update payment buttons after the checkout form was updated.
*/
export function refreshButtons() {
document.dispatchEvent(new Event(REFRESH_BUTTON_EVENT));
}
/**
* Sets up event listeners for various cart and checkout update events.
* When these events occur, it triggers a refresh of the payment buttons.
*
* @param {Function} refresh - Callback responsible to re-render the payment button.
*/
export function setupButtonEvents(refresh) {
const miniCartInitDelay = 1000;
const debouncedRefresh = debounce(refresh, 50);
// Listen for our custom refresh event.
document.addEventListener(REFRESH_BUTTON_EVENT, debouncedRefresh);
// Listen for cart and checkout update events.
document.body.addEventListener('updated_cart_totals', debouncedRefresh);
document.body.addEventListener('updated_checkout', debouncedRefresh);
// Use setTimeout for fragment events to avoid unnecessary refresh on initial render.
setTimeout(() => {
document.body.addEventListener('wc_fragments_loaded', debouncedRefresh);
document.body.addEventListener('wc_fragments_refreshed', debouncedRefresh);
}, miniCartInitDelay);
}

View file

@ -1,3 +1,5 @@
import { refreshButtons } from './ButtonRefreshHelper';
/**
* The MultistepCheckoutHelper class ensures the initialization of payment buttons
* on websites using a multistep checkout plugin. These plugins usually hide the
@ -105,17 +107,10 @@ class MultistepCheckoutHelper {
*/
checkElement() {
if (this.isVisible) {
this.refreshButtons();
refreshButtons();
this.stop();
}
}
/**
* Initializes the payment buttons on the visibility of wrapper.
*/
refreshButtons() {
document.dispatchEvent(new Event('ppcp_refresh_payment_buttons'));
}
}
export default MultistepCheckoutHelper;