2013-05-03 108 views
0

有沒有辦法更「自動」執行它?複雜類型對象的KnockoutJS映射數組

JavaScript代碼

var _json = { 
    Parents : [ 
     { ID: 1, Option: { ID: 0, Name: "Zero" } }, 
     { ID: 2, Option: { ID: 0, Name: "Zero" } } 
    ],   
    Options : [ 
    { ID: 0, Name: "Zero" }, 
    { ID: 1, Name: "One" }, 
    ] 
}; 

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

var viewModel = ko.mapping.fromJS(_json, mapping); 
ko.applyBindings(viewModel); 

HTML標記

<div data-bind="foreach: Parents"> 
    <p> 
    <b data-bind="text: $data.ID"></b> 
    <select name="x" data-bind="options: $parent.Options, optionsText: 'Name', value: $data.Option"></select> 
    <span data-bind="text: ko.toJSON($data)"></span> 
    </p> 
</div> 

下面是一個簡單的jsfiddle http://jsfiddle.net/BvVce/11/

回答

1

我有寫了簡單的遞歸映射函數。這是你正在尋找:

var _json = { 
    Parents : [ 
     { ID: 1, Option: { ID: 0, Name: "Zero" } }, 
     { ID: 2, Option: { ID: 0, Name: "Zero" } } 
    ],   
    Options : [ 
    { ID: 0, Name: "Zero" }, 
    { ID: 1, Name: "One" }, 
    ] 
}; 

function convertToObservable(obj) { 
    var newObj = {}, 
     key, 
     value; 

    if (!$.isPlainObject(obj)) { 
     return obj; 
    } 

    for (key in obj) { 
     if (obj.hasOwnProperty(key)) { 
      value = obj[key]; 
      // console.log(key + ':', value); 
      newObj[key] = $.isArray(value) 
       ? ko.observableArray($.map(value, convertToObservable)) 
       : $.isPlainObject(value) 
         ? ko.observable(convertToObservable(value)) 
         : ko.observable(value); 
     } 
    } 
    return newObj; 
} 

var viewModel = convertToObservable(_json); 
ko.applyBindings(viewModel); 

檢查出來的小提琴手:http://jsfiddle.net/tkirda/BvVce/12/

相關問題