Reputation: 77
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?
Upvotes: 2
Views: 5587
Reputation: 5147
I generally only like calling applybindings once on loading the page, but that does mean that you need to have all the observables you want to bind to created on page load. You could create a child view model for bios, with the observables you want to bind too, and then always use the update fromJSON method to populate it.
Have you tried:
function biosViewModel()
{
var self = this;
self.Caption = ko.observable();
self.Version = ko.observable();
}
var viewModel =
{
bios: ko.observable(new biosViewModel()),
cpu: ko.observable()
}
Then, in your success method:
ko.mapping.fromJSON(data, viewModel.bios());
to update the object with the data you get back from the server.
Upvotes: 1