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

40 lines
1,012 B
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
export default class extends CartBaseController {
2021-11-22 17:51:50 +00:00
static targets = ["counter"];
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
connect() {
2021-06-01 21:33:49 +00:00
if (!this.hasCounterTarget) {
2021-11-22 17:51:50 +00:00
console.error("Missing counter target");
return;
2021-06-01 21:33:49 +00:00
}
this.cart_count_event = this._cart_count_event.bind(this);
this.storage_event = this._storage_event.bind(this);
window.addEventListener("cart:counter", this.cart_count_event);
window.addEventListener("storage", this.storage_event);
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
if (!this.cart) return;
2021-06-01 21:33:49 +00:00
2021-11-22 17:51:50 +00:00
this.counter = this.cart.data.attributes.item_count;
2021-06-01 21:33:49 +00:00
}
disconnect() {
window.removeEventListener("cart:counter", this.cart_count_event);
window.removeEventListener("storage", this.storage_event);
}
2021-11-22 17:51:50 +00:00
set counter(quantity) {
this.counterTarget.innerText = quantity;
2021-06-01 21:33:49 +00:00
}
_cart_count_event(event) {
this.counter = event.detail.item_count;
}
_storage_event(event) {
if (event.key == "cart:counter") this.counter = event.newValue;
}
2021-06-01 21:33:49 +00:00
}