Book Image

Knockout.JS Essentials

Book Image

Knockout.JS Essentials

Overview of this book

Table of Contents (16 chapters)
KnockoutJS Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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,
        decreaseStock:decreaseStock
      };
    })();
  4. Update the add-to-cart-button component:

    this.addToCart = function() {
      ...
      if (item) {
        CartProductService.addUnit(item...