Skip to content

Instantly share code, notes, and snippets.

@cpres
Last active October 8, 2018 18:55
Show Gist options
  • Save cpres/cdbcf840201175737bae to your computer and use it in GitHub Desktop.
Save cpres/cdbcf840201175737bae to your computer and use it in GitHub Desktop.
Robust Shopify Cart JS Methods
__init__: function (p) {
var self = this;
self.initialConfig = p;
Shopify.queue = [];
},
addItem: function(prod,num, attr) {
var num = (num) ? num : 1;
this.pushQueue(prod,num,attr);
},
removeItem: function(prod,attr) {
this.pushQueue(prod,0,attr);
},
pushQueue: function(id,n,attr) {
Shopify.queue.push( {
variantId: id,
quantity: n,
attributes: attr
} );
this.moveAlong();
},
moveAlong: function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
if (request.attributes) {
Shopify.updateCartAttributes(request.attributes,function(){})
}
if (request.quantity > 0) {
Shopify.addItem(request.variantId, request.quantity, this.moveAlong);
} else {
Shopify.removeItem(request.variantId, this.moveAlong);
}
}
// If the queue is empty, we will redirect to the cart page.
else {
document.location.href = '/cart';
}
}
@cpres
Copy link
Author

cpres commented Dec 23, 2014

Usage:
VC.addItem({{id}},1,{'gift-box':true});
or
VC.removeItem({{id}},{'gift-box':''});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment