"use strict"; var vm = (function () { var catalog = ko.observableArray([ Product(1, "T-Shirt", 10.0, 20), Product(2, "Trousers", 20.0, 10), Product(3, "Shirt", 15.0, 20), Product(4, "Shorts", 5.0, 10), ]); var newProduct = Product("", "", "", ""); var clearNewProduct = function () { newProduct.name(""); newProduct.price(""); newProduct.stock(""); }; var addProduct = function (context) { var id = new Date().valueOf(); // random id from time var product = Product(id, context.name(), context.price(), context.stock()); catalog.push(product); clearNewProduct(); }; var searchTerm = ko.observable(""); var filteredCatalog = ko.computed(function () { // if catalog is empty return empty array if (!catalog()) { return []; } var filter = searchTerm().toLowerCase(); // if filter is empty return all the catalog if (!filter) { return catalog(); } //filter data var filtered = ko.utils.arrayFilter(catalog(), function (item) { var strProp = ko.unwrap(item["name"]).toLocaleLowerCase(); return (strProp.indexOf(filter) > -1); }); return filtered; }); var cart = ko.observableArray([]); var showCartDetails = function () { if (cart().length > 0) { $("#cartContainer").removeClass("hidden"); } }; var addToCart = function(data) { var item = null; var tmpCart = cart(); var n = tmpCart.length; while(n--) { if (tmpCart[n].product.id() === data.id()) { item = tmpCart[n]; } } if (item) { item.addUnit(); } else { item = new CartProduct(data, 0); item.addUnit(); tmpCart.push(item); } cart(tmpCart); }; // The cart-widget template var totalItems = ko.computed(function() { var tmpCart = cart(); var total = 0; tmpCart.forEach(function(item) { total += parseInt(item.units(), 10); }); return total; }) var grandTotal = ko.computed(function() { var tmpCart = cart(); var total = 0; tmpCart.forEach(function(item) { total += (item.units() * item.product.price()); }); return total; }) // The cart-item template var removeFromCart = function (data) { var units = data.units(); var stock = data.product.stock(); data.product.stock(units + stock); cart.remove(data); } // The cart template var hideCartDetails = function() { $('#cartContainer').addClass("hidden"); }; var showOrder = function () { $('#catalogContainer').addClass("hidden"); $('#orderContainer').removeClass("hidden"); } return { // first chapter searchTerm: searchTerm, catalog: filteredCatalog, newProduct: newProduct, addProduct: addProduct, // second chapter cart: cart, showCartDetails: showCartDetails, totalItems: totalItems, grandTotal: grandTotal, removeFromCart: removeFromCart, hideCartDetails: hideCartDetails, showOrder: showOrder }; })(); ko.applyBindings(vm);