From 48d61e59b99cd97fe0c0833bbe7506ce5da2c340 Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Thu, 27 May 2021 04:36:59 +0000 Subject: [PATCH] chap1->observables to refresh the ui automatically->Computed observables (non optimized) --- ko-cart/index.html | 14 ++++++++++++++ ko-cart/js/viewmodel.js | 37 ++++++++++++++++++++++++++++++------- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/ko-cart/index.html b/ko-cart/index.html index 6e1ed8e..5bcfc65 100644 --- a/ko-cart/index.html +++ b/ko-cart/index.html @@ -8,6 +8,7 @@

Catalog

+

Insert

@@ -52,6 +53,19 @@
+

Search

+
+ + Search + +
+ +

Products

Items: diff --git a/ko-cart/js/viewmodel.js b/ko-cart/js/viewmodel.js index 0fed83c..bc5c32f 100644 --- a/ko-cart/js/viewmodel.js +++ b/ko-cart/js/viewmodel.js @@ -17,18 +17,41 @@ var vm = (function () { var addProduct = function (context) { var id = new Date().valueOf(); // random id from time - var product = Product( - id, - context.name(), - context.price(), - context.stock() - ); + 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 fields = ["name"]; // we choose to filter by name + var i = fields.length; + while (i--) { + var prop = fields[i]; + var strProp = ko.unwrap(item[prop]).toLocaleLowerCase(); + if (strProp.indexOf(filter) !== -1) { + return true; + } + } + return false; + }); + return filtered; + }); + return { - catalog: catalog, + searchTerm: searchTerm, + catalog: filteredCatalog, newProduct: newProduct, addProduct: addProduct, };