在我的视图模型中,有一个名为projectLine的 observableArray 。该数组由 projectsWorked 对象组成。我需要得到数组中 projectsWorked.projectHourWork 的总和。我写了calcTotal()来计算总数。
function ViewModel() {
var self = this;
this.CheckIn = ko.observable();
this.CheckOut = ko.observable();
this.Lunch = ko.observable();
this.projectLine = ko.observableArray([new projectsWorked()]);
this.TimeForWork = ko.computed(function () {
return this.CheckIn() ? this.CheckOut() ? parseFloat(this.Lunch()) ? parseFloat(this.CheckOut()) - parseFloat(this.CheckIn()) - parseFloat(this.Lunch()) : parseFloat(this.CheckOut()) - parseFloat(this.CheckIn()) : 0 : 0;
}, this);
this.Rest = ko.observable();
this.RemainHour = ko.computed(function () {
return self.TimeForWork() ? self.Rest() ? self.WorkOnProject() ? parseFloat(self.TimeForWork()) - parseFloat(self.Rest()) - parseFloat(self.WorkOnProject()) : parseFloat(self.TimeForWork()) - parseFloat(self.Rest()) : parseFloat(self.TimeForWork()) : 0
}, this);
this.WorkOnProject = ko.observable();
this.grandTotal = ko.observable();
this.AddLine = function () {
alert('hello Add');
this.calcTotal();
this.projectLine.push(new projectsWorked());
};
//Problem Occurs in here
this.calcTotal = function () {
var total = 0;
alert('ABC');
ko.utils.arrayForEach(self.projectLine(), function () {
alert('BB');
alert(self.projectLine.projectWork);
total += self.projectLine.projectHourWork;
})
//$.each(self.projectLine, function () {
// totalh = parseFloat($('#txthour').val());
// total += totalh;
// alert(total);
//})
this.grandTotal = total;
// alert(total);
}
};
function projectsWorked() {
var self = this;
this.projectEnable = ko.observable(false);
this.hours = ko.observable();
this.projectHourWork=ko.computed(function () {
return this.hours();
}, this);
this.selectedProject = ko.observable();
this.removeLine = function (line) {
alert('hello Remove');
self.projectLine.removeLine(this);
};
};
var data = [
"ABC","CDE"
];
ko.applyBindings(new ViewModel());
但是这个计算给了我不正确的值。Firebug 将 self.projectLine.projectHourWork 值显示为未定义。这可能是什么原因?如何计算总数?