我目前正在尝试使用淘汰赛和javascript,但只是遇到了一个我无法解决的问题。
我有一个带有几个(简单,因为这只是为了测试)子虚拟机的视图模型,其中一个有一个计算变量,它应该显示另一个虚拟机数组的聚合成本。
当我通过 json 加载数据时,一切都会很好地填充,但计算结果仍然“未定义”。我已经尝试用“deferEvaluation”标记计算,但这没有帮助。
简而言之,这里是我的 jsfiddle http://jsfiddle.net/v73rxckf/9/
有任何想法吗?还是我一般做错了什么?
JS代码:
function Service(data) {
var self = this;
self.Cost = ko.observable(data.Cost);
}
function Action(data) {
var self = this;
self.Name = ko.observable(data.Name);
self.Dates = ko.observableArray(data.Dates);
self.Services = ko.observableArray(data.Services);
self.OverallCost = ko.computed(function() {
calculated = 0;
ko.utils.arrayForEach(self.Services(), function(item) {
calculated += parseFloat(ko.utils.unwrapObservable(item.Cost));
});
return calculated;
}, { deferEvaluation : true });
}
function Campaign(data) {
var self = this;
self.Name = ko.observable(data.Name);
self.Deadline = ko.observable(data.Deadline);
self.ActionList = ko.observableArray(data.ActionList);
}
function ApplicationViewModel () {
var self = this;
self.List = ko.observableArray([]);
$.ajax("/echo/json/", {
data: {
json: ko.toJSON(fakeData)
},
type: "POST",
dataType: 'json',
success: function(data) {
var mappedCampaigns = $.map(data, function(item) {
return new Campaign(item);
});
self.List(mappedCampaigns);
}
});
}
var fakeData = [{
"Name":"testname1",
"Deadline":"testdeadline1",
"ActionList":[
{
"Name":"testaction1",
"Dates":[ { "DateValue":"testdate1" }, { "DateValue":"testdate2" } ],
"Services":[ { "Cost":"100" }, { "Cost":"50" } ]
},
{
"Name":"testaction2",
"Dates":[ { "DateValue":"testdate1" }, { "DateValue":"testdate2" } ],
"Services":[{ "Cost":"100" }, { "Cost":"50" } ]
}
]
}];
ko.applyBindings(new ApplicationViewModel());