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:

  1. Create a folder called services.
  2. Inside it, create a file called ProductService.
  3. Create a singleton object and add the hasStock and decreaseStock 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, ...

Get KnockoutJS Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.