2017-04-26 26 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()); 
    }, []); 
}); 

此數組的更新時,無論是選擇形式的改變,或從這些形式之一在添加部/除去/。