2013-07-18 40 views
1

我是新來敲除和嘗試我認爲將是一個簡單的場景,但它只是不工作。選擇更改時,兩個輸入的更改都不會改變,並且選擇列表不會初始化爲selectedFormat。KnockoutJs映射查看模型複雜屬性

HTML:

<input type="text" data-bind="value: selectedFormat.id" /> 
<input type="text" data-bind="enable: selectedFormat.fields()[0].enabled" /> 

<select data-bind="options: formats, optionsText: 'name', value: selectedFormat" /> 

JS:

var data = { 
    formats: [ 
     { id: 1, name: 'Format 1', fields: [ 
      { id: 1, enabled: true }, 
      ]}, 
     { id: 2, name: 'Format 2', fields: [ 
      { id: 1, enabled: false }, 
      ]} 
     ], 
    selectedFormat: 
     { id: 2, name: 'Format 2', fields: [ 
      { id: 1, enabled: false }, 
      ]} 
    } 

var vm = ko.mapping.fromJS(data); 

ko.applyBindings(vm); 

http://jsfiddle.net/paulbau/ZnqNN/1/

回答

2

你幾乎沒有在你的小提琴,所有的部件都沒有,他們只是需要被連接。

Te映射插件不會自動爲包含complexs對象的屬性創建observables。因此,默認情況下,您的selectedFormat在映射之後不會是可觀察的。因爲你想寫value: selectedFormat它必須是可觀察的,因此你需要一個自定義的映射配置,這使得selectedFormat觀察到:

var mapping = { 
    'selectedFormat': { 
     create: function(options) { 
      return ko.observable(ko.mapping.fromJS(options.data)); 
     } 
    } 
} 

如果definied一個create功能,那麼這樣就需要你負責其價值的映射在options.data的創建函數內部調用ko.mapping.fromJS來映射selectedFormat內的值也是可觀察的。

然後,你需要告訴ko.mapping使用你的映射配置有:

var vm = ko.mapping.fromJS(data, mapping); 

而現在只需要改變你的綁定,因爲selectedFormat將是可觀察到的,所以你需要用selectedFormat()得到它的價值:

<input type="text" data-bind="value: selectedFormat().id" /> 
<input type="text" data-bind="enable: selectedFormat().fields()[0].enabled" /> 

演示JSFiddle.

如果你想在初始選擇的工作,那麼你的地圖平需要查找的,而不是創建一個新對象通過ID選擇的項目:

var mapping = { 
    'selectedFormat': { 
     create: function(options) { 
      var selected = ko.utils.arrayFirst(options.parent.formats(), 
       function(item){ 
        return item.id() == options.data.id; 
      }); 
      return ko.observable(selected); 
     } 
    } 
} 

演示JSFiddle.

+0

好,謝謝,這是得到了相關性問題。但是選擇列表仍然不會初始化爲什麼selectedFormat最初設置爲,例如,如果我更改了我的JSON數據,例如selectedFormat = {id:2,name:'Format 2'},則選擇列表仍將加載格式1。 – user380689

+0

@ user380689請看我更新的答案。 – nemesv

+0

完美!非常感謝 – user380689