2020-04-24 13:41:32 +00:00
|
|
|
const Event = window.Event || null;
|
|
|
|
|
2020-07-14 19:46:44 +00:00
|
|
|
/**
|
|
|
|
* Wrapper function to dispatch an event so it's compatible with IE11.
|
|
|
|
*
|
|
|
|
* @param {string} name Name of the event to dispatch.
|
|
|
|
* @param {boolean} bubbles Whether the event bubbles.
|
|
|
|
* @param {boolean} cancelable Whether the event is cancelable.
|
|
|
|
*/
|
|
|
|
const dispatchEvent = ( name, bubbles = false, cancelable = false ) => {
|
2020-04-24 13:41:32 +00:00
|
|
|
// In IE, Event is an object and can't be instantiated with `new Event()`.
|
|
|
|
if ( typeof Event === 'function' ) {
|
2020-07-14 19:46:44 +00:00
|
|
|
const event = new Event( name, {
|
|
|
|
bubbles,
|
|
|
|
cancelable,
|
2020-04-24 13:41:32 +00:00
|
|
|
} );
|
|
|
|
document.body.dispatchEvent( event );
|
|
|
|
} else {
|
|
|
|
const event = document.createEvent( 'Event' );
|
2020-07-14 19:46:44 +00:00
|
|
|
event.initEvent( name, bubbles, cancelable );
|
2020-04-24 13:41:32 +00:00
|
|
|
document.body.dispatchEvent( event );
|
|
|
|
}
|
|
|
|
};
|
2020-07-14 19:46:44 +00:00
|
|
|
|
|
|
|
// This is a hack to trigger cart updates till we migrate to block based cart
|
|
|
|
// that relies on the store, see
|
|
|
|
// https://github.com/woocommerce/woocommerce-gutenberg-products-block/issues/1247
|
|
|
|
export const triggerFragmentRefresh = () => {
|
|
|
|
dispatchEvent( 'wc_fragment_refresh', true, true );
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Function that listens to a jQuery event and dispatches a native JS event.
|
|
|
|
* Useful to convert WC Core events into events that can be read by blocks.
|
|
|
|
*
|
|
|
|
* @param {string} jQueryEventName Name of the jQuery event to listen to.
|
|
|
|
* @param {string} nativeEventName Name of the native event to dispatch.
|
|
|
|
* @param {boolean} bubbles Whether the event bubbles.
|
|
|
|
* @param {boolean} cancelable Whether the event is cancelable.
|
|
|
|
*
|
|
|
|
* @returns {Function} Function to remove the jQuery event handler. Ideally it
|
|
|
|
* should be used when the component is unmounted.
|
|
|
|
*/
|
|
|
|
export const translateJQueryEventToNative = (
|
|
|
|
jQueryEventName,
|
|
|
|
nativeEventName,
|
|
|
|
bubbles = false,
|
|
|
|
cancelable = false
|
|
|
|
) => {
|
|
|
|
// @ts-ignore -- jQuery is window global
|
|
|
|
if ( typeof jQuery !== 'function' ) {
|
|
|
|
return () => void null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const eventDispatcher = () => {
|
|
|
|
dispatchEvent( nativeEventName, bubbles, cancelable );
|
|
|
|
};
|
|
|
|
|
|
|
|
// @ts-ignore -- jQuery is window global
|
|
|
|
jQuery( document ).on( jQueryEventName, eventDispatcher );
|
|
|
|
// @ts-ignore -- jQuery is window global
|
|
|
|
return () => jQuery( document ).off( jQueryEventName, eventDispatcher );
|
|
|
|
};
|