I'm receiving json data from WCF service and want to map it to my viewModel.
JSON DATA:
{"bios" :
{ "Caption" : "something",
"Version": "something else",
....
}
}
My HTML part is the following:
<ul class="biosContentUL">
<li class="biosContentLI">
<p>
<b>Caption: </b><span data-bind="text: bios.Caption"></span>
</p>
</li>
<li class="biosContentLI">
<p>
<b>Version: </b><span data-bind="text: bios.Version"></span>
</p>
</li>
.......
</ul>
My ViewModel is the following:
var viewModel = {
bios: ko.observable(),
cpu: ko.observable(),
.....
}
$(document).ready(function () {
ko.applyBindings(viewModel);
}
);
I'm trying to use mapping plugin, but can't make it work correctly.
function showBios() {
var response = $.ajax({
type: "GET",
datatype: "json",
url: "...",
success: function (data) {
objJS= jQuery.parseJSON(data);
viewModel.bios(ko.mapping.fromJS(objJS));
// I also tried this:
// ko.mapping.fromJS(objJS, {}, viewModel);
}
});
The following code works, but I also have observableArrays in my ViewModel, so I loose their content if I call applyBindings() one more time.
viewModel.bios = ko.mapping.fromJS(objJS);
ko.applyBindings(viewModel);
How can I map received data to my viewModel property "bios" ? Is it a good approach to have multiple viewmodels for each part of the page, so in each model I can declare simple properties, not complex objects?