问题
I am going crazy trying to find a solution for my problem. I have a JS object which has a hierarchical structure and the level of hierarchy is unknown. Making use of JQuery template and Knockout JS i can get the tree structure with <ul>
& <li>
but my requirement is, for each child, I need to render a new Row
in a Table
So lets say my structure is:
{
Name: 'First',
Total: 100,
Set: [
{
Name: 'First_1', Total: 30,
Set: [{Name: 'First_1_1', Total: 10}, {Name: 'First_1_2', Total: 20}]
},
{ Name: 'First_2', Total: 0 }
]
}
The table should look like:
<table width="100%">
<tbody>
<tr><th>Name</th><th>Total</th></tr>
<tr><td>First</td><td>100</td></tr>
<tr><td>First_1</td><td>30</td></tr>
<tr><td>First_1_1</td><td>10</td></tr>
<tr><td>First_1_2</td><td>20</td></tr>
<tr><td>First_2</td><td>0</td></tr>
</tbody>
</table>
Following is the fiddle I have come up with: http://jsfiddle.net/paragnair/xpsa4/
If I was using ul
li
, i could call the template recursively by using
<ul data-bind="template: {name: 'tree1', foreach: Set}"></ul>
but since my template itself starts with a <tr>
I am not sure how do i call the template without writing a node with the data-bind="template:{...}
part? The initial call will work because its on the <tbody>
but I cannot have a tbody
within a tbody
to recursively call the template to render other tr
.
I hope this explanation was sufficient. Let me know if you need more details. Any help is appreciated.
回答1:
You can recursively call a template from inside that template, that combined with the foreach's $data context property allows you do do what you're looking for... I'm terrible at explaining things so I updated your jsfiddle to do what you're looking for, http://jsfiddle.net/xpsa4/5/
来源:https://stackoverflow.com/questions/11509324/recursive-tr-with-knockout-js-and-jquery-template