2021-05-27 13:57:20 +10:00
|
|
|
"use strict";
|
2021-05-27 14:22:28 +10:00
|
|
|
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
|
|
|
|
|
2021-05-27 14:36:59 +10:00
|
|
|
var product = Product(id, context.name(), context.price(), context.stock());
|
2021-05-27 14:22:28 +10:00
|
|
|
catalog.push(product);
|
|
|
|
clearNewProduct();
|
|
|
|
};
|
|
|
|
|
2021-05-27 14:36:59 +10:00
|
|
|
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;
|
|
|
|
});
|
|
|
|
|
2021-05-27 14:22:28 +10:00
|
|
|
return {
|
2021-05-27 14:36:59 +10:00
|
|
|
searchTerm: searchTerm,
|
|
|
|
catalog: filteredCatalog,
|
2021-05-27 14:22:28 +10:00
|
|
|
newProduct: newProduct,
|
|
|
|
addProduct: addProduct,
|
|
|
|
};
|
2021-05-27 12:46:22 +10:00
|
|
|
})();
|
2021-05-27 14:22:28 +10:00
|
|
|
ko.applyBindings(vm);
|