function Item(id, price, quantity, productId) {
this.id = id;
this.price = ko.observable(price);
this.quantity = ko.observable(quantity);
this.productId = ko.observable(productId);
//dependentObservable to display total (not internationalized)
this.total = ko.computed(function() {
return viewModel.formatCurrency(this.quantity() * this.price());
}, this);
//writable dependentObservable to parse currency input
this.editPrice = ko.dependentObservable({
//return a formatted price
read: function() {
return viewModel.formatCurrency(this.price());
},
//if the value changes, make sure that we store a number back to price
write: function(newValue) {
this.price(viewModel.parseCurrency(newValue));
},
owner: this
});
//manual subscription to default in the wholesale price whenever the product changes (technically we could do this in the write function of the writeable dependentObservable, but better to keep it focused on reading/writing the single field).
this.productId.subscribe(function(newProductId) {
var newProduct = ko.utils.arrayFirst(viewModel.productCatalog, function(product) {
return product.id == newProductId;
});
this.price(newProduct.wholesale);
}.bind(this));
}
var viewModel = {
items: ko.observableArray([]),
productCatalog: [
{
id: 1,
name: "Pencil",
wholesale: 1},
{
id: 2,
name: "Pen",
wholesale: 1},
{
id: 3,
name: "Ruler",
wholesale: 4},
{
id: 4,
name: "Eraser",
wholesale: 2}
],
addItem: function() {
this.items.push(new Item(0, 1, 1, 1));
},
removeItem: function(itemToRemove) {
this.items.remove(itemToRemove);
},
//not internationalized, for sample purposes
formatCurrency: function(value) {
return "$" +...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.