我试图总结一组给定项目的总成本。每个项目都有一个总成本,即价格 * 数量。这计算很好。但是,我现在试图总结所有项目的总成本。
考虑到所有项目总数都是单独计算的,我该如何总结它们?这是在 viewModel、模型还是两者之外完成的?
这是小提琴 http://jsfiddle.net/B9rAt/3/中的代码。就目前而言,总数不会显示。如果您删除总数中的“*数量”位,它将显示,但这只是商品价格的总和,而不是商品的总和。
function ItemEntry(ID, inventory, price) {
var self = this;
self.ID = ID;
self.inventory = inventory;
self.price = price;
self.selectedQuantity = ko.observable(); //returned value (trying to get it at least!)
self.itemTotal = ko.computed(function() {
var price = self.price;
var quantity = self.selectedQuantity();
var total = price * quantity;
return total ? "$" + total.toFixed(2) : "None";
});
self.formattedPrice = ko.computed(function() {
var price = self.price;
return price ? "$" + price.toFixed(2) : "None";
});
}
function EntryViewModel(newItem) {
var self = this;
self.newItem = newItem;
//start the array with some items
self.itemNumbers = ko.observableArray([
new ItemEntry("1", 3, 4.99) //ID, inventory, price
,new ItemEntry("6", 2, 10.00) //ID, inventory, price
]);
//Compute total cost here
self.totalCost = ko.computed(function() {
var total = 0;
var quantity = self.selectedQuantity();
for (var i = 0; i < self.itemNumbers().length; i++) {
total += Number(self.itemNumbers()[i].price * quantity);
}
return total;
});
self.removeItem = function(item) { self.itemNumbers.remove(item) }
}
//populate the select list with values up to the number in inventory (ex, if inventory is 3, it will fill with 0-7)
ko.bindingHandlers.quantityDropdown = {
init: function(quantityDropdown, inventory, EntryViewModel) {
var quantity = ko.utils.unwrapObservable(inventory());
for(var i = 1; i <= quantity; i++){
$(quantityDropdown).append('<option value="' + i + '">' + i + '</option>');
}
}
};
ko.applyBindings(new EntryViewModel());