chap2 -> Creating templates -> The catalog template -> part 3

Add CartProduct.js
Add addToCart method in viewmodel
Rename product.js to Product.js
chap2
Jason Zhu 2022-04-19 23:38:16 +10:00
parent d18a1efd31
commit e52b7bb978
4 changed files with 59 additions and 1 deletions

View File

@ -95,7 +95,8 @@
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/knockout-3.2.0.js"></script>
<!-- app -->
<script type="text/javascript" src="js/models/product.js"></script>
<script type="text/javascript" src="js/models/Product.js"></script>
<script type="text/javascript" src="js/models/CartProduct.js"></script>
<script type="text/javascript" src="js/viewmodel.js"></script>
</body>
</html>

View File

@ -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
}
}

View File

@ -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