jeffharrell / minicart

The minicart is a great way to improve your PayPal shopping cart integration.
MIT License
501 stars 209 forks source link

Reset Cart on Add? #241

Closed vireous closed 10 years ago

vireous commented 10 years ago

Hi Jeff,

I'm really enjoying working with minicart so far, just hoping you can help me with something that I'm not finding how to do in the documentation or the code. I'd like to set up a page with five items, each with their own "Add to Cart" button, but I would like to be able to empty the cart before adding the item through the button.

Basically, if I have Item A, Item B, and Item C, I'd like the user to only be able to add one of the three to their cart. Then, if the cart has an item in it and the user selects another item, the original selection would be removed from the cart and the current selection added.

Right now, I've been able to get the cart to reset on adding, using:

paypal.minicart.cart.on('add', function(){
    paypal.minicart.reset();
});

But I'm not able to get it to add anything after the reset. Maybe I'm going about this entirely the wrong way. Hopefully you can help. Thanks!

jeffharrell commented 10 years ago

That's the right approach. Off the top of my head and untested, how about trying something like the following where you check for the presence of items in the cart first:

paypal.minicart.cart.on('add', function() {
    if (this.items().length > 0) {
        this.reset();
    }
});
vireous commented 10 years ago

Ah, of course! It's one of those "been racking my brain for hours and can't think of a possible solution things." The code you listed didn't seem to do anything, but it seems like the on add ups the count of the items before the if statement can run. So I changed it to check for greater than 1, and instead of resetting, just removing the first item in the index, like so:

paypal.minicart.cart.on('add', function() {
    if (this.items().length > 1) {
        paypal.minicart.cart.remove(0);
    }
});

Seems to be working based on testing. Thanks for the suggestion and the help, Jeff!

jeffharrell commented 10 years ago

Yes, that would make more sense ;) Glad you got it working.