我试图在knockout中创建一些计算变量。问题是在映射后向子项的子项添加新元素时,我的计算变量不会使用添加到observableArray的新元素进行更新
请帮助你?
这是代码,也附加了一个jsFiddle
由于
https://jsfiddle.net/r3pasftb/18/
var data = {id: 45, Name: "Whatever Name",
Stages: [{stageID: 1, StageName: "Stage1", Team: [{Name: "Team1", FeesAllocated: 500}, {Name: "Team2", FeesAllocated: 200}]}, {stageID: 1, StageName: "Stage1", Team: []}]};
mappingTeam = function(options){
var teamSelf = options != null ? options : this;
teamSelf.Name = ko.observable(options != null ? options.Name : 0);
teamSelf.FeesAllocated = ko.observable(options != null ? options.FeesAllocated : 0);
return teamSelf;
};
mappingStages = function(options){
var stageSelf = options != null ? options : this;
stageSelf.StageID = ko.observable(options != null ? options.StageID : 0);
stageSelf.StageName = ko.observable(options != null ? options.StageName : 0);
stageSelf.Team = ko.observableArray(ko.utils.arrayMap(stageSelf.Team, mappingTeam ));
stageSelf.Length = ko.computed(function(){
return stageSelf.Team().length;
});
//I need this value to be updated, but do nothing with new elements created after the mapping
stageSelf.TotalStageFees = ko.computed(function(){
var total = 0;
ko.utils.arrayForEach(stageSelf.Team(), function (team) {
total += team.FeesAllocated();
});
return total;
});
return stageSelf;
};
var mappingOptions = {
create: function (options) {
return new function () {
var self = options.data;
//Here map Stage Array
self.Stages = ko.observableArray(ko.utils.arrayMap(self.Stages, mappingStages ));
ko.mapping.fromJS(self, {}, this);
};
}
};
//Map my object with child and subchild
var self = ko.mapping.fromJS(data, mappingOptions);
console.log(self.Stages()[0].TotalStageFees())
console.log(self.Stages()[0].Length())
//Add new TeamMember to first Stage
self.Stages()[0].Team.push(new mappingTeam({Name: "Team3", FeesAllocated: 50}));
//As you see, non TotalStageFees or Lenght are updated
console.log(self.Stages()[0].TotalStageFees())
console.log(self.Stages()[0].Team())
console.log(self.Stages()[0].Length())