我有一个浮点数组weeklyAmounts
,在子对象中定义a
。在父对象b
中,我有一个对象数组a
,需要从所有子对象计算第 1 周的小计,从所有子对象计算第2 周的小a
计a
等。
我的问题:
- 通过阅读淘汰文档,可观察到的数组会跟踪诸如删除或添加之类的事件,但不会跟踪单个对象的状态更改,因此在我的情况下,即使用户
week1Amount
从 GUI 更改,它也不会触发计算值。真的吗? - 令我惊讶的是,
week1Amount
从 GUI 更改后,我没有看到 viewmodel 中的值发生变化。我在这里错过了什么吗? - 鉴于需要什么,最好的解决方案是什么?
我不工作的代码如下:
function a(id, name, week1Amount, week2Amount, week3Amount, week4Amount,
week5Amount, week6Amount, week7Amount, week8Amount, week9Amount, week10Amount...) {
var self = this;
self.id = id;
self.name = name;
self.week1Amount = ko.observable(week1Amount);
self.week2Amount = ko.observable(week2Amount);
self.week3Amount = ko.observable(week3Amount);
self.week4Amount = ko.observable(week4Amount);
self.week5Amount = ko.observable(week5Amount);
self.week6Amount = ko.observable(week6Amount);
self.week7Amount = ko.observable(week7Amount);
self.week8Amount = ko.observable(week8Amount);
self.week9Amount = ko.observable(week9Amount);
self.week10Amount = ko.observable(week10Amount);
self.week11Amount = ko.observable(week11Amount);
self.week12Amount = ko.observable(week12Amount);
};
function b(bid, bname, as) {
var self = this;
self.id= bid;
self.name = bname;
self.as = as;
self.week1Sum = ko.computed(function () {
var sum = 0.0;
$(self.as).each(function (index, aItem) {
sum += aItem.week1Amount();
});
return sum;
});
//rest of code is omitted for brevity.
};
var objBs = [];
$(objAs).each(function (index, aItem) {
var newA = new a(aItem.ID, aItem.Name,
aItem.WeeklyAmount[0],aItem.WeeklyAmount[1],aItem.WeeklyAmount[2],aItem.WeeklyAmount[3],
aItem.WeeklyAmount[4],aItem.WeeklyAmount[5],aItem.WeeklyAmount[6],....);
objBs.push(newA);
});
var vmB = new b(1,"someName", objBs);
ko.applyBindings(vmB, document.getElementById("showBs"));