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

The Services module


Services are also singletons, like resources, so follow the same steps as the resources module:

  1. Open the services/ProductService.js file.

  2. Create the top hierarchy module:

    var Shop;
    Shop = Shop || {};
  3. Create the Resources namespace:

    Shop.Services = Shop.Services || {};
  4. Define ProductService:

    Shop.Services.ProductService = (function(){
    })();
  5. In this case the service has no dependencies.

  6. Finally, set the following code in the services/ProductService.js file. Since in the application the resources are singleton, extend the resource with the methods used in the following code:

    var Shop;
    Shop = Shop || {};
    Shop.Services = Shop.Services || {};
    Shop.Services.ProductService = (function(Product) {
      var hasStock = function (product) {
        return product.stock() > 0;
      };
    
      var decreaseStock = function (product) {
        var s = product.stock();
        if (s > 0) {
          s--;
        }
        product.stock(s);
      };
    
      var clone = function (product) {
        return Product(product.id(), product.name...