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