Reputation: 3568
We have the cart.item_count displayed in the header. That's fine for most pages. But on one page, we dynamically add items to the cart, and we want the changes to be reflected in the cart summary in the header.
I'm thinking we need RivetsJS for this to work; so we'd have a one-way binding. I tried a couple of ways:
<span rv-text="cart.item_count"></span>
And:
{ cart.item_count }
The first showed up empty, the second displayed the curly braces and cart.item_count, literally.
What am I doing wrong? Do I need to do a rivets.bind() somewhere?
Upvotes: 2
Views: 8277
Reputation: 470
Try this:
<strong data-cart-render="item_count"></strong>
and make sure your JS looks like this:
<script type="text/javascript">
jQuery(function() {
CartJS.init({{ cart | json }}, {
"dataAPI": **true**,
"requestBodyClass": "loading",
rivetsModels: {
"customer": {{ customer | json }},
"product": {{ product | json}},
"cart" : {{ cart | json }}
}
});
});
</script>
Upvotes: 0
Reputation: 11682
As @Ronnie commented, you should use Shopify's Ajax API.
There's plenty of other questions & answers on Stack Overflow with examples of how to do this, here's just a few:
$.ajax({
type: 'GET',
url: 'http://your-store.myshopify.com/cart.json',
dataType: 'json',
success: function(data) {
var item_count = data.item_count;
// Update the item count in your header here...
}
});
You could also use Shopify's jQuery wrapper library. See Shopify.getCart()
:
// ---------------------------------------------------------
// GET cart.js returns the cart in JSON.
// ---------------------------------------------------------
Shopify.getCart = function(callback) {
jQuery.getJSON('/cart.js', function (cart, textStatus) {
if ((typeof callback) === 'function') {
callback(cart);
}
else {
Shopify.onCartUpdate(cart);
}
});
};
Upvotes: 2