Mapping sample

by graphicsxp

HTML

<script src="https://raw.github.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<table>
    <tr>
        <td data-bind="text: name"></td>
    </tr>
    <tr>
        <td>
            <div data-bind="template: 'personTemplate'"></div>    
        </td>
    </tr>
</table>

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

CSS

input { margin: 2px; }
ul { margin-left: 10px; }

JavaScript

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

var viewModel = ko.mapping.fromJS(originalData);

ko.applyBindings(viewModel);