From 9cb6be067a6ce084b5d325836de519b7a15a5588 Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Thu, 27 May 2021 04:22:28 +0000 Subject: [PATCH] chap1->Observables to refresh the UI automatically->Inserting elements in collections 1. Learned with binding for context switch 2. Learned textInput for text binding 3. click binding for event driven --- ko-cart/index.html | 29 +++++++++++++++++++++++++- ko-cart/js/viewmodel.js | 45 ++++++++++++++++++++++++++++++----------- 2 files changed, 61 insertions(+), 13 deletions(-) diff --git a/ko-cart/index.html b/ko-cart/index.html index 10303e2..fd303a2 100644 --- a/ko-cart/index.html +++ b/ko-cart/index.html @@ -7,8 +7,35 @@

Catalog

+ +
+
+
+ +
+
+
+
+ +
+
+
+
+ +
+
+
+
+ +
+
+
+ Items: - + diff --git a/ko-cart/js/viewmodel.js b/ko-cart/js/viewmodel.js index ec897ae..0fed83c 100644 --- a/ko-cart/js/viewmodel.js +++ b/ko-cart/js/viewmodel.js @@ -1,15 +1,36 @@ "use strict"; -var vm = (function() { - - var catalog = [ - Product(1, "T-Shirt", 10.00, 20), - Product(2, "Trousers", 20.00, 10), - Product(3, "Shirt", 15.00, 20), - Product(4, "Shorts", 5.00, 10) - ]; +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), + ]); - return { - catalog: catalog - }; + 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(); + }; + + return { + catalog: catalog, + newProduct: newProduct, + addProduct: addProduct, + }; })(); -ko.applyBindings(vm); \ No newline at end of file +ko.applyBindings(vm);