I have recursive template that is bound to my model. The problem is that I am modifying the object one at a time so if I click on the next one and I try to load the new object the template doesn't update.
My Template:
<div class="portlet-body" id="details-container" data-bind="template: { name: 'packageTemplate', data: viewModel.packageElements() }"></div>
MyModel:
var viewModel;
function packageElementViewModel(data) {
var self = this;
self.packageElements = ko.observable({ Description: ko.observable(), Children: ko.observableArray() });
}
My Initialization:
$.ajax({
'type': 'POST',
'url': 'http://www.someurl.com/',
'data': { PackageId: 1},
'success': function (data) {
viewModel.packageElements = ko.observable(ko.mapping.fromJS(data));
ko.applyBindings(viewModel);
});
When I select a new package I call this code and I update the variable but the UI doesn't update.:
var id = PackageSummary.packageTable.fnGetData($(this).get(0))['Id'];
$.ajax({
'type': 'POST',
'url': 'http://www.someurl.com',
'data': { PackageId: id },
'success': function (data) {
viewModel.packageElements = ko.observable(ko.mapping.fromJS(data));
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
This is my data:
{
"Description":"Top",
"Children":[
{
"Description":"Second-Level 1",
"Children":[
{
"Description":"Third Level 1",
"Children":[]
},
{
"Description":"Third Level 2",
"Children":[]
},
{
"Description":"Third Level 3",
"Children":[]
}
]
},
{
"Description":"Second Level 2":[
{
"Description":"Third Level 1",
"Children":[]
},
{
"Description":"Third Level 2",
"Children":[]
},
{
"Description":"Third Level 3",
"Children":[]
}
]
}
]
}
I believe the problem is you are resetting the packageElements
in you success method on the ajax call
'success': function (data) {
viewModel.packageElements = ko.observable(ko.mapping.fromJS(data));
}
that is breaking the bindings with the elements that are set up when you call ko.applyBindings(viewModel)
Instead what you want to do is just set the Description
and Children
properties on the observables that are already in the viewModel
'success': function (data) {
viewModel.packageElements().Description(data.Description);
viewModel.packageElements().Children(data.Children);
}
I made an example doing basically this same thing but with different data. http://jsfiddle.net/vGuHU/
Also, as a side note. From the code you posted there is no real reason for packageElements
to be a ko.observable()