我感到非常困惑,为什么即使我的成分在列表中正确填充并呈现,当我更改例如第一成分的“剂量参考系统”的值时,它又会与剂量参考系统的值相混淆。数组中的最后一项?
每行中的值不会根据该行中的值进行更新
任何帮助将不胜感激:
这是小提琴:http://jsfiddle.net/makeitmorehuman/C6AvC/
此处参考的代码是:
function ingredient(data) {
ingr = this;
ingr.Name = ko.observable(data.Name);
ingr.UnitCost = ko.observable(data.UnitCost);
ingr.DRS = ko.observable(data.DRS);
ingr.DP = ko.observable(data.DP);
ingr.PercenChange = ko.computed(function () {
return Math.round(ingr.DP() - ingr.DRS());
});
ingr.RawMaterialRS = ko.computed(function () {
return Math.round((ingr.DRS() / 100) * ingr.UnitCost() * 10000);
});
ingr.RawMaterialCostProp = ko.computed(function () {
return Math.round((ingr.DP() / 100) * ingr.UnitCost() * 10000);
});
ingr.CostDifference = ko.computed(function () {
return Math.round(ingr.RawMaterialCostProp() - ingr.RawMaterialRS());
});
}
function ingredientsData() {
return [
{ "Name": "Skimmed milk", "UnitCost": 0.40, "DRS": 70, "DP": 87 },
{ "Name": "Cream 40% fat", "UnitCost": 1.80, "DRS": 18, "DP": 9 },
{ "Name": "Skim Milk Powder", "UnitCost": 2.5, "DRS": 12, "DP": 1 },
{ "Name": "N-Dulge SAI", "UnitCost": 3.5, "DRS": 0, "DP": 2 },
{ "Name": "Novation Indulge 1720", "UnitCost": 3.9, "DRS": 0, "DP": 1 }
];
}
function NovationIndulge() {
var self = this;
self.Ingredients = ko.observableArray();
self.init = function () {
ko.utils.arrayForEach(ingredientsData(), function (item) {
self.Ingredients.push(new ingredient(item));
});
};
function SumOfItems(propertyToSum) {
var total = 0;
ko.utils.arrayForEach(self.Ingredients(), function (item) {
total = parseInt(total) + parseInt(item[propertyToSum]());
});
return total;
}
self.TotalDRS = ko.computed(function () { return SumOfItems("DRS"); });
self.TotalDP = ko.computed(function () { return SumOfItems("DP"); });
self.TotalCostDiff = ko.computed(function () { return SumOfItems("CostDifference"); });
self.TotalRawMaterialRS = ko.computed(function () { return SumOfItems("RawMaterialRS"); });
self.TotalRawMCP = ko.computed(function () { return SumOfItems("RawMaterialCostProp") });
self.AnnualFinishedProduct = ko.observable(4000);
self.TotalCostSavingP1000 = ko.computed(function () { return self.TotalCostDiff() * -1 });
self.TotalAnnualSaving = ko.computed(function () {
return self.TotalCostSavingP1000() * self.AnnualFinishedProduct() / 1000;
});
}
var NI = new NovationIndulge();
NI.init();
ko.applyBindings(NI);
答案 0 :(得分:1)
我的第一个猜测是因为你定义了
function ingredient(data) {
ingr = this;
...
没有 var
关键字,它将创建一个全局属性(属于窗口)。
然后,每次原型中的一个函数运行时,东西就会混乱。
答案 1 :(得分:1)