sutty-base-jekyll-theme/_packs/controllers/order_controller.js

83 lines
2 KiB
JavaScript
Raw Normal View History

2021-11-22 17:51:50 +00:00
import { CartBaseController } from "./cart_base_controller";
2021-06-01 21:33:49 +00:00
/*
* Renders the order table. All products are stored on localStorage, so
* we just fetch that information and render the cart contents using
* Liquid.
*/
export default class extends CartBaseController {
2021-11-22 17:51:50 +00:00
static targets = ["cart", "subtotal", "itemCount"];
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
async connect() {
const products = this.products;
const site = window.site;
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
this.render({ products, site });
this.subtotalUpdate();
this.itemCountUpdate();
this.storage_event = this._storage_event.bind(this);
this.cart_subtotal_update_event =
this._cart_subtotal_update_event.bind(this);
window.addEventListener("storage", this.storage_event);
window.addEventListener(
"cart:subtotal:update",
this.cart_subtotal_update_event
);
2021-06-01 21:33:49 +00:00
}
disconnect() {
window.removeEventListener("storage", this.storage_event);
window.removeEventListener(
"cart:subtotal:update",
this.cart_subtotal_update_event
);
}
async _storage_event(event) {
if (!event.key?.startsWith("cart:item:")) return;
const products = this.products;
const site = window.site;
this.render({ products, site });
this.subtotalUpdate();
this.itemCountUpdate();
}
_cart_subtotal_update_event(event) {
this.itemCountUpdate();
this.subtotalUpdate();
2021-06-01 21:33:49 +00:00
}
/*
* Download the item template and render the order
*/
2021-11-22 17:51:50 +00:00
render(data = {}) {
const template = window.templates[this.data.get("itemTemplate")];
2021-10-28 13:00:00 +00:00
2021-11-22 17:51:50 +00:00
this.engine
.parseAndRender(template, data)
.then((html) => (this.cartTarget.innerHTML = html));
2021-06-01 21:33:49 +00:00
}
/*
* Updates the subtotal
*
* XXX: This also updates the currency
*/
2021-11-22 17:51:50 +00:00
subtotalUpdate() {
if (!this.cart) return;
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
this.subtotalTarget.innerText = this.cart.data.attributes.display_total;
2021-06-01 21:33:49 +00:00
}
2021-11-22 17:51:50 +00:00
itemCountUpdate() {
if (!this.hasItemCountTarget) return;
if (!this.cart) return;
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
this.itemCountTarget.innerText = this.cart.data.attributes.item_count;
2021-06-01 21:33:49 +00:00
}
}