I've been attempting to make a simple cart functionality in my app. I'm using polymer for my application and the cart and products are all in one single component. I'm using coffeescript as default but any help in javascript will be equally helpful.
The functionality is to increase the quantity of a product and simultaneously increase the quantity in the cart.
This is how I am increasing the quantity count on the page
increaseQty:(e)->
tmp = @filteredItems.findIndex (i) ->
i == e.model.item
@set 'filteredItems.' + tmp + '.quantity', e.model.item.quantity + 1
@addToCart e
The "addToCart" function is super simple. I just push the current item into the cart.
addToCart:(e)->
#i = 0
@push 'cart', e.model.item
My problem is when I add quantity more than "1", it replicates the item in the cart, the last instance being the one I need.
I have tried comparing with a "while" loop to check if an item is already present in the cart and tried to increase the quantity but it doesn't work like it should. I'm assuming there is a better way to do this. Any help would be appreciated.
You can use the any
function of underscore.js
to check if an item is already in the cart before insert.
Assuming model.item
has a property id
which can uniquely identify the item.
require 'underscore'
found = _.any cart, (elem) -> elem.id == e.model.item.id
if !found:
@addToCart e
I did not test the code. Just a general idea.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.