1

With a JSON like that:

JSON string

{ 
  "SelectedOption" : {}, 
  "Options" : [ 
    { "ID": 0, "Name": "Zero" },
    { "ID": 1, "Name": "One" }
  ] 
}

The question is: How can I tell to mapping plugin that the SelectedOption property is an ko.observable?

Client Code

var _json = '{
               "SelectedOption" : {},
               "Options" : [   
                 { "ID": 0, "Name": "Zero" },
                 { "ID": 1, "Name": "One" }    
               ]
             }';

var viewModel = ko.mapping.fromJSON(_json);
ko.applyBindings(viewModel);

I wrote a jsfiddle to show the problem http://jsfiddle.net/BvVce/3/

Tocco
  • 1,655
  • 11
  • 14
  • A working example with a complex object http://jsfiddle.net/BvVce/8/ – Tocco May 03 '13 at 14:43
  • Refer to this answer I have answered similar question [here][1] [1]: http://stackoverflow.com/a/24670804/2764258 – AR M Jul 10 '14 at 07:47

1 Answers1

4

You have to provide a custom mapping to indicate to the mapping function how it should do it. I've updated your fiddle.

Here's the custom mapping, and the changed call to ko.mapping:

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

var viewModel = ko.mapping.fromJSON(_json, mapping);

And then, in your HTML, you have to add the "()" characters to SelectedOption because it is now an observable, like this:

<span data-bind="text: SelectedOption().ID"></span>
Jalayn
  • 8,934
  • 5
  • 34
  • 51
  • 1
    Thanks. What about an array of objects with a property like that? Do you have any idea? – Tocco May 03 '13 at 13:43
  • You mean an array of selectable options ? If that's the case, instead of returning a ko.observable you can return a ko.observableArray mapped with ko.utils.arrayMap I guess. – Jalayn May 03 '13 at 13:48
  • @Tocco I updated another version of your fiddle with an observable array allowing to select multiple options so you can check out how it can be done: http://jsfiddle.net/BvVce/6/ – Jalayn May 03 '13 at 13:52
  • no I mean a ko.observableArray containing objects like that: { "ID": 9, "SelectedOption": { "ID": 1, "Name": "One" } } ... I want to observe the "SelectedOption" property of each array object. – Tocco May 03 '13 at 14:16
  • @Tocco well yes you can, it's very similar to what I've done in my updated fiddle. – Jalayn May 03 '13 at 14:22
  • @Tocco took me some time, but here: http://jsfiddle.net/BvVce/9/ I could not find a way other than "rebinding" the properly selected option manually... I think you could ask another question with that, I am curious if there is a better way... – Jalayn May 03 '13 at 15:08