获取嵌套数组取决于下拉选择并使其可观察

时间:2017-04-26 10:06:16

标签: knockout.js

我坚持使用以下工具:

Feature I need to implement

逻辑如下:取决于用户选择的表单,获取与此表单相关的所有部分。例如:如果用户选择名称为“T-01”的表单,则必须使用与此表单相关的所有部分填充sections数组。并且每个部分都必须可以观察以进一步计算。

这是我的表单模型:

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']);

这里是Section模型:

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);
}

我在根级别上有几个模型,但我不在此处包含它,不确定是否需要它。

1 个答案:

答案 0 :(得分:0)

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

据我所知的代码(不幸的是,不是一个工作片段......),有两个可观察的集合:

  • Name字符串
  • 的可观察数组
  • 具有类似Form属性的Name视图模型的可观察数组

您可以使用The most efficient way to implement an integer based power function pow(int, int)Array.prototype.filter创建一个新的表单数组,如下所示:

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

用简单的英语说:“给我一张表格列表,这些表格的名字出现在我选择的名字列表中”。

现在,如果我们将这个代码包装在一个计算并创建所有可观察属性的依赖项中,你会得到:

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

只要需要及其中一个依赖项更新,就会计算更新。因此,当您从allForms添加/删除表单时,Name属性发生更改或FormOptions更改时。

现在您有了所选表单的列表,您可以创建第二个计算表:部分列表。这是所选表单各部分的串联:

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

当所选表单发生更改时,或者在其中一个表单中添加/删除某个部分时,此数组会更新。