forked from woocommerce/woocommerce-blocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-store-cart-event-listeners.ts
87 lines (77 loc) · 2.06 KB
/
use-store-cart-event-listeners.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* External dependencies
*/
import { useEffect } from '@wordpress/element';
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
import { dispatch } from '@wordpress/data';
import { translateJQueryEventToNative } from '@woocommerce/base-utils';
interface StoreCartListenersType {
count: number;
remove: () => void;
}
declare global {
interface Window {
wcBlocksStoreCartListeners: StoreCartListenersType;
}
}
const refreshData = ( e ): void => {
const eventDetail = e.detail;
if ( ! eventDetail || ! eventDetail.preserveCartData ) {
dispatch( storeKey ).invalidateResolutionForStore();
}
};
const setUp = (): void => {
if ( ! window.wcBlocksStoreCartListeners ) {
window.wcBlocksStoreCartListeners = {
count: 0,
remove: () => void null,
};
}
};
const addListeners = (): void => {
setUp();
if ( window.wcBlocksStoreCartListeners.count === 0 ) {
const removeJQueryAddedToCartEvent = translateJQueryEventToNative(
'added_to_cart',
`wc-blocks_added_to_cart`
) as () => () => void;
const removeJQueryRemovedFromCartEvent = translateJQueryEventToNative(
'removed_from_cart',
`wc-blocks_removed_from_cart`
) as () => () => void;
document.body.addEventListener(
`wc-blocks_added_to_cart`,
refreshData
);
document.body.addEventListener(
`wc-blocks_removed_from_cart`,
refreshData
);
window.wcBlocksStoreCartListeners.count = 0;
window.wcBlocksStoreCartListeners.remove = () => {
removeJQueryAddedToCartEvent();
removeJQueryRemovedFromCartEvent();
document.body.removeEventListener(
`wc-blocks_added_to_cart`,
refreshData
);
document.body.removeEventListener(
`wc-blocks_removed_from_cart`,
refreshData
);
};
}
window.wcBlocksStoreCartListeners.count++;
};
const removeListeners = (): void => {
if ( window.wcBlocksStoreCartListeners.count === 1 ) {
window.wcBlocksStoreCartListeners.remove();
}
window.wcBlocksStoreCartListeners.count--;
};
export const useStoreCartEventListeners = (): void => {
useEffect( () => {
addListeners();
return removeListeners;
}, [] );
};