2017-04-26 25 views
0

我坚持与执行以下操作:获取嵌套数组取决于下拉选择,使之可观察

Feature I need to implement

的逻辑如下:取决于用户选择的形式,获得与此相关的表格所有部分。例如:如果用户选择名称为“T-01”的表格,那么章节数组必须填写与该表格相关的所有章节。并且每个部分必须是可观察的以便进一步计算。

这里是我的表单模型:

function Form(name, title, max, total, sections) { 
    this.Name = ko.observable(name); 
    this.Title = ko.observable(title); 
    this.MAX = ko.observable(max); 
    this.Total = ko.observable(total); 
    this.Sections = ko.observableArray(sections); 
    this.addSection = function() { 
    this.Sections.push(new Section()); 
    }.bind(this); 
} 

var FormOptions = ko.observableArray(['T-01', 'T-02', 'T-03']); 

而且这里的部分型号:

function Section(section, criteria, is, cs, nc, fc, totalInitialScores, totalFinalScores) { 
    this.Section = ko.observable(section); 
    this.Criteria = ko.observable(criteria); 
    this.IS = ko.observable(is); 
    this.CS = ko.observable(cs); 
    this.NC = ko.observable(nc); 
    this.FC = ko.observable(fc); 
    this.TotalInitialScores = ko.observable(totalInitialScores); 
    this.TotalFinalScores = ko.observable(totalFinalScores); 
} 

我有一个根级别的几个型号,但我不包括在这里,不知道如果需要的话。

回答

0

您可以使用ko.pureComputedko.computed属性来创建数据的动态选择。

据我可以从你所示的代码(不幸的是,没有一个工作片断......),有两个观察集合告诉:

  • Name字符串的可观测阵列
  • 的具有类似Name财产

您可以使用Array.prototype.filterArray.prototype.includes创建的形式,像这样一个新的数组Form视图模型可观察到的数组:

const selectedForms = allForms.filter(f => selectedNames.includes(f.name)); 

其中,用简单的英语说:“返回给我一个名单出现在我的选定名称列表中的表单”。现在

,如果我们在计算包裹此代码,并创建依赖于所有观察到的性能,您可以:

var selectedForms = ko.pureComputed(function() { 
    return allForms().filter(function(form) { 
    return FormOptions().includes(form.Name()); 
    }); 
}); 

无论何时,只要需要,并updates.So它的一个依赖这种计算的更新,当您添加/从allForms中删除表格,Name属性更改或FormOptions更改。

现在您已经选择了一个表格列表,您可以创建第二个计算表格:一个表格列表。这是您的选定形式的部分的串联:

var selectedFormsSections = ko.pureComputed(function() { 
    return selectedForms().reduce(function(allSections, form) { 
    return allSections.concat(form.Sections()); 
    }, []); 
}); 

此数组的更新时,无论是选择形式的改变,或从这些形式之一在添加部/除去/。