-
Notifications
You must be signed in to change notification settings - Fork 5
/
headerCart.es6
118 lines (102 loc) · 2.62 KB
/
headerCart.es6
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
(() => {
const DOM = {
$cart: $('.js-cart-header'),
orderTable: '#js-order-list',
cartWrapper: '.js-cart-wrapper',
resetCart: '.js-reset-cart',
removeFromCart: '.js-cart-remove',
};
const config = {
storageKey: 'rendered-cart',
};
const init = () => {
loadCart();
setUpListeners();
};
function setUpListeners() {
mediator.subscribe(
'onCartUpdate',
(_, data) => {
render(data.header);
saveCart(data.header);
},
showCart,
);
mediator.subscribe('onSuccessOrder', reloadCart);
// Since product's list in Cart dropdown is dynamic, we bind events on static parent
DOM.$cart.on('click', DOM.resetCart, clear);
DOM.$cart.on('click', DOM.removeFromCart, remove);
}
/**
* Load cart lazily to prevent caching of its content
* and reach ability to store shared cache for pages.
*/
function loadCart() {
const renderedCart = localStorage.getItem(config.storageKey);
if (renderedCart) {
render(renderedCart);
} else {
reloadCart();
}
}
function saveCart(state) {
localStorage.setItem(config.storageKey, state);
}
function reloadCart() {
server.getCart()
.then((data) => {
render(data.header);
saveCart(data.header);
});
}
/**
* Remove product with the given id from cart.
*/
function remove(event) {
const id = $(event.target).data('product-id');
const quantity = $(event.target).data('product-count');
server.removeFromCart(id)
.then((data) => {
mediator.publish('onCartUpdate', data);
mediator.publish('onProductRemove', [{ id, quantity }]);
});
}
/**
* Remove everything from cart.
*/
function clear() {
const productsData = $(DOM.removeFromCart).map((_, el) => {
const $el = $(el);
return {
id: $el.data('product-id'),
quantity: $el.data('product-count'),
};
}).get();
server.flushCart()
.then((data) => {
mediator.publish('onCartUpdate', data);
mediator.publish('onCartClear', [productsData]);
});
}
/**
* Perform header cart dropdown animation for every page, except order page.
*/
function showCart() {
if ($(DOM.orderTable).size() > 0) return;
const $cartWrapper = $(DOM.cartWrapper);
$cartWrapper.addClass('active');
// timeout value now is under ux/ui experiments
setTimeout(() => {
$cartWrapper.removeClass('active');
}, 5000);
}
/**
* Render new Cart's html.
* @param html
*/
function render(html) {
DOM.$cart.html(html);
configs.initScrollbar();
}
init();
})();