Using knockout.js, is it possible to bind to a property of a child object of a JSON object from the server? Specifically, if I'm given an object from the server that looks like this:
var obj = {
list: [ { key: "a", value: 1 },
{ key: "b", value: 2 },
{ key: "c", value: 3 }
],
selected: {
key: "",
value: null
}
};
I create a viewModel from this javascript object via the "mapping" plugin:
var viewModel = ko.mapping.fromJS(obj);
And I bind list to a <select> tag like so:
<select data-bind="options: list, optionsText: 'key',
optionsValue: 'value',
value: selected">
</select>
I've assigned the value to be the selected property of my viewModel. This means, upon selecting an option, I can successfully query viewModel.selected.key() and viewModel.selected.value() in code and get the up-to-date values.
However, I am unable to bind the selected item's key or value data to be displayed on a span. For instance, this doesn't display my selected value:
<span data-bind="text: selected.value"></span>
Can I do what I want? Do I need to resort to using a real simple template to establish proper context (ie: selected)?
I have an example of the situation here. I've even tried specifically mapping the child selected object to be an observable itself, but with no luck (see commented out mapping call with the additional options).