A library for subscribing to and executing changes in the cart using Ajax API.
Executing functionality is done via dispatch calls as demonstrated further in this documentation.
Follow the setup instructions to enable it in your own store.
Testing in this Store
Simply add products to the cart and inspect what happens when we change product quantity or remove a product.
Notice that when you remove a product, or change it's quantity, the line's subtotal and the foother's subtotal automatically adjusts.
This is because each time the quantity is changed, it "dispatches" a `changeCart` event to SMCart, which is received by it's listeners
Inspecting the Code
Check `src/cart.js` of the source code at about line 63 where it describes a `listenToSMCart()` function
listenToSMCart() {
const originalDawnOnUpdate = (allUpdates) => {
// ...
}
SMCart.on("changeCart", originalDawnOnUpdate);
}
This tells our system to listen for a `changeCart` event and get update cart data from it. Line 135 tells us how this code is executed:
updateQuantity(line, quantity, name) {
this.enableLoading(line);
SMCart.dispatch({
type: "changeCart",
line,
quantity,
sections: this.getSectionsToRender().map((section) => section.section),
sections_url: window.location.pathname
})
.catch(() => {
this.querySelectorAll('.loading-overlay').forEach((overlay) => overlay.classList.add('hidden'));
const errors = document.getElementById('cart-errors') || document.getElementById('CartDrawer-CartErrors');
errors.textContent = window.cartStrings.error;
})
.finally(() => {
this.disableLoading(line);
});
}
The function updateQuantity is currently being called whenever the quantity field changes. Inside it, is a call to `dispatch which asks SMCart to update the quantity and once it's done, it'll update any listener in the page.
There are cleaner ways to do this like separating the listner for the line item subtotal and footer subtotal, even introducing a cart drawer that updates whenever an `addToCart` is dispatched. For now this demonstrates well how we can separate the data updates, and action dispatches.
Further Implementation
Implementation efforts are ongoing for this with the clickup task but we may expect further demo of the usage of this library on Raw & Fresh.