I just started using knockoutjs and I'm trying to build a dynamic treeview. To simplify, I removed everything that's not related to the problem. the treeview will consist of nested UL-tags.
The html:
<div id="pnlDestinations">
<ul data-bind="template: { name: 'GroupTemplate', foreach: Groups }"></ul>
</div>
<script type="text/html" id="GroupTemplate">
<li>
<a href="#" data-bind="text: GroupName, click: function() { RetrieveDestinations($data); }"></a>
<ul data-bind="template: { name: 'DestinationTemplate', foreach: Destinations }"></ul>
</li>
</script>
<script type="text/html" id="DestinationTemplate">
<li>
<a href="#" data-bind="text: DestinationName"></a>
</li>
</script>
The code:
function ViewModel(groups) {
Groups = ko.mapping.fromJS(groups);
RetrieveDestinations = function (group) {
$.getJSON('GetDestinations?id=' + group.GroupId(), function (data) {
group.Destinations(ko.mapping.fromJS(data));
});
}
}
$(function () {
$.getJSON("GetGroups", function (data) {
ko.applyBindings(new ViewModel(data));
});
});
So I'm binding the treeview at two levels (using 2 templates), but i'm only retrieving one level in "GetGroups" (Destinations exists, but is an empty array).
Destinations are retrieved in the RetrieveDestinations() methods when the group is clicked and should replace the empty array in the group. However, they don't show up in my treeview.
The binding of the treeview should be correct because if I include the destinations in "GetGroups" everything is rendered correctly.