简体   繁体   English

更新购物车并删除购物车中的多余物品

[英]Update cart and remove redundant items in cart

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. 我默认使用coffeescript,但是javascript中的任何帮助同样有用。

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. “ addToCart”功能非常简单。 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. 我的问题是,当我添加的数量大于“ 1”时,它会复制购物车中的商品,最后一个实例是我需要的那个。

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. 我尝试过与“ while”循环进行比较,以检查购物车中是否已存在某种物品,并试图增加数量,但它无法正常工作。 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. 您可以使用underscore.jsany函数在插入之前检查商品是否已经在购物车中。

Assuming model.item has a property id which can uniquely identify the item. 假设model.item具有可以唯一标识项目的属性id

 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. 只是一个大致的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM