简体   繁体   中英

Creating total cost function in Knockout shopping cart

I am very new to js knockout and have been tasked with adding functionality to a shopping cart. I have created a function for the total cost of the items in the cart but it doesn't work (code is highlighted below).

My question is: how do I change this function, or create a new one, that outputs the total cost of the items in the cart, and that changes if an item is removed or the quantity of an item is changed?

Here's the code and a brief explanation of the cart:

http://jsfiddle.net/b4atrw2g/5/

The cart has two main sections. In the 'Add New Item' section, the user enters the name, cost and quantity of the item, then clicks 'Add Item'.

The item then appears in the 'Items in Cart' section with the cost and quantity. The user is still able to change the quantity of the item when it's in the cart.

I've created a function called 'getTotalCost', but that outputs the total cost of the item before it is added to the cart, and disappears once the item is added to the cart.

Here's the function:

 viewModel.getTotalCost = ko.pureComputed(function() { var total = 0; total += viewModel.newItemPrice() * viewModel.newItemQuantity(); return total; }, viewModel); 

Thank you in advance.

viewModel.getTotalCost = ko.pureComputed(function() 
{
    var total = 0;
    arr = viewModel.itemsInCart();
    for (i = 0; i< arr.length;i++)
       total += arr[i].price * arr[i].quantity;
    return total; 
}

http://jsfiddle.net/b4atrw2g/6/

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.

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