在我的視圖模型中有一個名爲projectluine的observableArray。該數組由projectsWorked對象組成。我需要獲得數組中的projectsWorked.projectHourWork的總和。我寫了calcTotal()來計算總數。在knockoutjs中使用observableArray進行計算
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值顯示爲未定義。這可能是什麼原因?我如何計算總數?
爲什麼你聲明變量var self = this;'然後你繼續使用'this'而不是'self'? –