This repository has been archived by the owner on Apr 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
cart.js
66 lines (58 loc) · 1.92 KB
/
cart.js
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
// start with an IIFE to keep the global namespace clean
(function () {
// UI class for changing the user interface
class CartView {
// we only have one cart,
// so we no longer need to clone a template and
// append to a body
constructor(element) {
// here we only need the cart table
// to append rows to,
// so only one element reference to store:
this.container = element;
// subscribe to updateCart topic
PubSub.subscribe("updateCart", (products) => this.updateCart(products));
}
// this is a "private" method, meant to be used from other methods only
// hence the _
_rowTemplate(productData) {
return `<tr><td>${productData.name}</td><td class="has-text-right">${productData.price}</td></tr>`;
}
// build HTML based on product data and row template
_buildCartHTML(productList) {
let cartContent = "";
for (const product of productList) {
cartContent += this._rowTemplate(product);
}
return cartContent;
}
// this is the public API for our cart UI objects:
// method to change the UI by only changing the
// content of the cart table
updateCart(products) {
this.container.innerHTML = this._buildCartHTML(products);
}
}
// this way the other JS files can also use this class
window.CartView = CartView;
// Cart class for adding items to cart
class CartModel {
constructor() {
this.items = [];
// subscribe to the addToCart topic
PubSub.subscribe("addToCart", (item) => this.addItem(item));
}
// API for Cart object
addItem(item) {
this.items.push(item);
// publish updated item list to updateCart topic
// when cart content updates
PubSub.publish("updateCart", this.getItems());
}
getItems() {
return this.items;
}
}
// this way the other JS files can also use this class
window.CartModel = CartModel;
})();