From e52b7bb9787a8e733b81283b7cc2708ca464373c Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Tue, 19 Apr 2022 23:38:16 +1000 Subject: [PATCH] chap2 -> Creating templates -> The catalog template -> part 3 Add CartProduct.js Add addToCart method in viewmodel Rename product.js to Product.js --- ko-cart/index.html | 3 +- ko-cart/js/models/CartProduct.js | 39 ++++++++++++++++++++ ko-cart/js/models/{product.js => Product.js} | 0 ko-cart/js/viewmodel.js | 18 +++++++++ 4 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 ko-cart/js/models/CartProduct.js rename ko-cart/js/models/{product.js => Product.js} (100%) diff --git a/ko-cart/index.html b/ko-cart/index.html index d078bea..45fdc00 100644 --- a/ko-cart/index.html +++ b/ko-cart/index.html @@ -95,7 +95,8 @@ - + + diff --git a/ko-cart/js/models/CartProduct.js b/ko-cart/js/models/CartProduct.js new file mode 100644 index 0000000..5a722b4 --- /dev/null +++ b/ko-cart/js/models/CartProduct.js @@ -0,0 +1,39 @@ +var CartProduct = function (product, units) { + "unit strict"; + + // Each cart product is composed of the product and units of the product we want to buy + var _product = product, + _units = ko.observable(units); // number of units to add or remove + + var subtotal = ko.computed(function() { + return _product.price() * _units(); + }); + + var addUnit = function () { + var u = _units(); // read number of units from observable + var _stock = product.stock(); + if (_stock === 0 ) { + return; + } + _units(u + 1); // assign observable with new unit + _product.stock(--_stock); // reduce inventory of stock by decrease unit from product + }; + + var removeUnit = function () { + var u = _units(); + var _stock = _product.stock(); + if (u === 0) { + return; + } + _units(u - 1); + _product.stock(++_stock); + }; + + return { + product: _product, + units: _units, + subtotal: subtotal, + addUnit: addUnit, + removeUnit: removeUnit + } +} \ No newline at end of file diff --git a/ko-cart/js/models/product.js b/ko-cart/js/models/Product.js similarity index 100% rename from ko-cart/js/models/product.js rename to ko-cart/js/models/Product.js diff --git a/ko-cart/js/viewmodel.js b/ko-cart/js/viewmodel.js index 889e3b3..8e88005 100644 --- a/ko-cart/js/viewmodel.js +++ b/ko-cart/js/viewmodel.js @@ -47,6 +47,24 @@ var vm = (function () { $("#cartContainer").removeClass("hidden"); } }; + var addToCart = function(data) { + var item = null; + var tmpCart = cart(); + var n = tmpCart.length; + while(n--) { + if (tmpCart[n].product.id() === data.id()) { + item = tmpCart[n]; + } + } + if (item) { + item.addUnit(); + } else { + item = new CartProduct(data, 0); + item.addUnit(); + tmpCart.push(item); + } + cart(tmpCart); + }; return { // first chapter