KnockoutJS复杂类型对象的映射数组

时间:2013-05-03 18:18:11

标签: json knockout.js knockout-mapping-plugin

有没有办法更“自动”地做到这一点?

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 个答案:

答案 0 :(得分: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);

在fiddler上查看:http://jsfiddle.net/tkirda/BvVce/12/