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

69 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-06-01 21:33:49 +00:00
import { CartBaseController } from './cart_base_controller'
/*
* 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 {
static targets = [ 'cart', 'subtotal', 'itemCount' ]
async connect () {
const products = this.products
2021-10-28 17:59:19 +00:00
const site = window.site
2021-06-01 21:33:49 +00:00
this.render({ products, site })
this.subtotalUpdate()
this.itemCountUpdate()
this.subscribe()
}
/*
* Subscribe to change on the storage to update the cart.
*/
subscribe () {
window.addEventListener('storage', async event => {
2021-07-09 22:05:53 +00:00
if (!event.key?.startsWith('cart:item:')) return
2021-06-01 21:33:49 +00:00
const products = this.products
2021-10-28 17:59:19 +00:00
const site = window.site
2021-06-01 21:33:49 +00:00
this.render({ products, site })
this.subtotalUpdate()
this.itemCountUpdate()
})
window.addEventListener('cart:subtotal:update', event => {
this.itemCountUpdate()
this.subtotalUpdate()
})
}
/*
* Download the item template and render the order
*/
render (data = {}) {
2021-10-28 13:00:00 +00:00
const template = window.templates[this.data.get('itemTemplate')]
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
*/
subtotalUpdate () {
if (!this.cart) return
this.subtotalTarget.innerText = this.cart.data.attributes.display_total
}
itemCountUpdate () {
if (!this.hasItemCountTarget) return
if (!this.cart) return
this.itemCountTarget.innerText = this.cart.data.attributes.item_count
}
}