I am having trouble iterating over my json data with knockout.
My view model looks like :
var ViewModel = function () {
var self = this;
self.Summary = ko.observableArray();
$.getJSON('some api url', function(result) {
ko.mapping.fromJS(result, {}, self);
});
}
ko.applyBindings(new ViewModel());
My JSON data looks like :
{
Summary: {
Details: [
{
Name: "Foo",
Id: 1,
Detail: "Some Data"
},
{
Name: "Bar",
Id: 2,
Detail: "Another Data"
}
],
SummaryOverview: "BlahBlah",
AnotherObject: [
{
Name: "My Name"
AnotherChildObject: [
{
name:"some name"
}
]
}
]
}
}
My question is do I iterate thru my data this way:
<div data-bind="foreach: Summary">
<div data-bind="text: Details.Detail"></div>
</div>
OR
<div data-bind: "foreach: Summary.Details">
<div data-bind="text: Detail"></div>
</div>
How do I display the Detail? The HTML above is not working for me.
Thank you very much!!
The problem with
ko.mappingis that your observables will be replaced with new observables. To clarify, theSummary, which is an observableArray, will be replaced by a new observableArray byko.mapping.There are two ways to remedy this. The first alternative is to wait with the
applyBindingsuntil the real array has been created:Alternative 2 is to bootstrap the viewmodel with initial (empty) data. If you apply
ko.mappingon an empty array, the next call toko.mappingwill update the existing array rather than overwrite it. Like so:I usually go with alternative 2. Alternative 1 will cause a delay before
ko.applyBindingsis called, which might cause some UI flicker (and unwanted elements may be visible, etc).