0

Is there a way to do it more "automatically" ?

JavaScript code

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 markup

<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>

Here is a sample jsfiddle http://jsfiddle.net/BvVce/11/

1 Answer 1

1

I have wrote simple recursive mapping function. Is that what you are looking for:

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);

Check it out on fiddler: http://jsfiddle.net/tkirda/BvVce/12/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.