Recursive binding knockout.js

I am trying to make a complex knockout binding (at least for a novice like me).

Consider the following data:

var originalData = {
id: 1,
name: "Main",
children: [ { id: 2, name: "bob", children: []}, { id: 3, name: "ted", children: [{id: 5, name:"albert"}, {id: 9, name: "fred"}]} ],
selectedChild:  { id: 2, name: "bob" }
};

<table>
<tr>
    <td data-bind="text: name"></td>
</tr>
<tr data-bind="if: children().length > 0">
    <td>
        <select data-bind="options: children,
            optionsText: function(item){
                return item.name;
                    }, 
            optionsCaption: 'Choose...'"></select>       
    </td>
</tr>

Well, that was the easy part.

The tough part is that whenever an item is selected in the list, if this item has children, then a new flag should appear under it. Its data source will be the children of the selected item in the first selection field. Of course, this could go on with any level of depth.

How do I solve this knockout problem?

I put together a sample of what I have on jsfiddle: http://jsfiddle.net/graphicsxp/qXZjM/

+5
source share
1 answer

, script. script :

<div data-bind="template: 'personTemplate'"></div>

<script type="text/ko" id="personTemplate">
    <span data-bind="text: name"></span>
    <select data-bind="options: children, optionsText: 'name', optionsCaption: 'Choose',  value: selectedChild"></select>
    <!-- ko if: selectedChild -->
    <div data-bind="template: { name: 'personTemplate', data: selectedChild }"></div>
    <!-- /ko -->
</script>


Update:

computed, , ( ), if.

self.showChildren = ko.computed(function() {
    return self.selectedChild()
        && self.selectedChild().children().length > 0;
});

if, , parens. , ; , , "" .

if: selectedChild() && selectedChild().children().length > 0

+9

All Articles