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, ...

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.