2012-11-20 47 views
2

我正在學習Knockout.js,我有關於更新嵌套數據的問題,我正在做什麼可能或需要重新考慮我的模型?觀察更新ObservableArray內的數據

這裏的數據視圖模型:

this.menu = ko.observableArray([ 
    {text: "one", 
     children: [{text: "child 1.1", checked: true},{text: "child 1.2", checked: false}]}, 
    {text: "two", 
     children: [{text: "child 2.1", checked: false},{text: "child 2.2", checked: true}]}, 
    {text: "three", 
     children: [{text: "child 3.1", checked: false}]} 
]); 

這裏的小提琴:

http://jsfiddle.net/4aqrg/1/

的數據在最後寫出來的,所以我們可以看到它的狀態。

我想在HTML視圖中更改複選框時更新選中的值,但這不會發生。在狀態變化的背後,我想採取一些行動。在這種情況下,該操作將顯示圖中的數據系列(仍然要完成該部分)。

由於提前, 馬特

回答

3

在你的榜樣的問題是,你所做的陣列觀察的,但個別屬性無法觀測。

你需要使每個「檢查」屬性ko.observable爲了它的更新。

像這樣:

this.menu = ko.observableArray([ 
     {text: "one", 
      children: [{text: "child 1.1", checked: ko.observable(true)},{text: "child 1.2", checked: ko.observable(false)}]}, 
     {text: "two", 
      children: [{text: "child 2.1", checked: ko.observable(false)},{text: "child 2.2", checked: ko.observable(true)}]}, 
     {text: "three", 
      children: [{text: "child 3.1", checked: ko.observable(false)}]} 
    ]); 

如果您希望文本也可觀察的,你必須來包裝,以及:ko.observable( 「子1.1」)

+0

真棒,謝謝。我的意圖是數據來自JSON AJAX,所以我想我得看看這個映射。 – Matt

+0

閱讀了地圖插件,它可以滿足你的需求。 http://knockoutjs.com/documentation/plugins-mapping.html – Geoff

+0

很酷,感謝您的確認 – Matt