chap1->observables to refresh the ui automatically->Computed observables (non optimized)

This commit is contained in:
jason.zhu 2021-05-27 04:36:59 +00:00
parent 60608b8b6c
commit 48d61e59b9
2 changed files with 44 additions and 7 deletions

View File

@ -8,6 +8,7 @@
<body>
<h1>Catalog</h1>
<h2>Insert</h2>
<form class="form-horizontal" role="form" data-bind="with:newProduct">
<div class="form-group">
<div class="col-sm-12">
@ -52,6 +53,19 @@
</div>
</form>
<h2>Search</h2>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-search"></i> Search</span
>
<input
type="text"
class="form-control"
data-bind="textInput: searchTerm"
/>
</div>
<h2>Products</h2>
<strong>Items:</strong>
<span data-bind="text:catalog().length"></span>
<table class="table">

View File

@ -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,
};