Creating the product service
If you look in the models/product.js
file, you can see that the model contains some logic:
var hasStock = function () { return _product.stock() > 0; }; var decreaseStock = function () { var s = _product.stock(); if (s > 0) { s--; } _product.stock(s); };
We are going to move this logic and some more to a service with the following steps:
Create a folder called
services
.Inside it, create a file called
ProductService
.Create a singleton object and add the
hasStock
anddecreaseStock
functions, as follows:var ProductService = (function() { var hasStock = function (product) { return product.stock() > 0; }; var decreaseStock = function (product) { var s = product.stock(); if (s > 0) { s--; } product.stock(s); }; return { hasStock:hasStock, decreaseStock:decreaseStock }; })();
Update the
add-to-cart-button
component:this.addToCart = function() { ... if (item) { CartProductService.addUnit(item...