generated from boboko/starter
32 lines
1.1 KiB
JavaScript
32 lines
1.1 KiB
JavaScript
import { Controller } from '@hotwired/stimulus'
|
|||
|
|
|
||
|
|
// 3dealer-side glue for the checkout module. The module owns the cart and emits
|
||
|
|
// `bbk-cart:updated` {count, total} on window after every change; this reflects
|
||
|
|
// the line count on the header bag icon. How (or whether) that count is shown
|
||
|
|
// is the host's call — hence this lives here, not in the module.
|
||
|
|
export default class extends Controller {
|
||
|
|
static targets = ['badge']
|
||
|
|
|
||
|
|
connect() {
|
||
|
|
this.onUpdate = (event) => this.render(event.detail?.count ?? 0)
|
||
|
|
window.addEventListener('bbk-cart:updated', this.onUpdate)
|
||
|
|
}
|
||
|
|
|
||
|
|
disconnect() {
|
||
|
|
window.removeEventListener('bbk-cart:updated', this.onUpdate)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Header cart icon click — there's no separate cart page, the drawer IS
|
||
|
|
// the cart. `bbk-cart:open` is the module's own event, already listened
|
||
|
|
// for by bbk-cart-controller.
|
||
|
|
open() {
|
||
|
|
window.dispatchEvent(new CustomEvent('bbk-cart:open'))
|
||
|
|
}
|
||
|
|
|
||
|
|
render(count) {
|
||
|
|
if (!this.hasBadgeTarget) return
|
||
|
|
this.badgeTarget.textContent = String(count)
|
||
|
|
this.badgeTarget.hidden = count < 1
|
||
|
|
}
|
||
|
|
}
|