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 CartProduct service


The cart item service also extracts the logic of the CartProduct model. To create this service, follow these steps:

  1. Create a file called CartProductService.js in the service folder.

  2. Remove the addUnit and removeUnit methods from the CartProduct model.

  3. Update the service with these methods:

    var CartProductService = (function() {
    
      var addUnit = function (cartItem) {
        var u = cartItem.units();
        var _stock =  cartItem.product.stock();
        if (_stock === 0) {
          return;
        }
        cartItem.units(u+1);
        cartItem.product.stock(--_stock);
      };
    
      var removeUnit = function (cartItem) {
        var u =  cartItem.units();
        var _stock =  cartItem.product.stock();
        if (u === 0) {
          return;
        }
        cartItem.units(u-1);
        cartItem.product.stock(++_stock);
      };
    
      return {
        addUnit:addUnit,
        removeUnit:removeUnit
      };
    })();