问题
How to access the index of the grand parent in the nested loop?
For example:
<div class="loop" data-bind="foreach: rows">
<div class="nested-loop" data-bind="foreach: cells">
<div class ="nested-nested-loop" data-bind="foreach: candidates, css : {selected : $root.isSelected($parentContext.$parentContext.$index(), $parentContext.$index(), $index())}">
Candidate index: <span data-bind="text: $index()"></span>
Cell index: <span data-bind="text: $parentContext.$index()"></span>
Row index: <span data-bind="text: $parentContext.$parentContext.$index()"></span>
</div>
</div>
</div>
I tried to bind like this:
css : {selected : $root.isSelected($parentContext.$parentContext.$index(), $parentContext.$index(), $index())}
and I encountered:
TypeError:
$parentContext.$parentContext.$index
is not a function
回答1:
If you want to display the index form the grand-parent you need the $parentContext
of the $parentContext
, so you need to write:
Row index: <span data-bind="text: $parentContext.$parentContext.$index()"></span>
http://jsfiddle.net/fjYsG/
It is not working in your css
binding because you have the binding on the same element as your foreach
so the binding context is not correctly set at their point.
You can solve this with moving the foearch
and the css
on different elements like using the containrless binding systax:
<div class="loop" data-bind="foreach: rows">
<div class="nested-loop" data-bind="foreach: cells">
<!-- ko foreach: candidates -->
<div class="nested-nested-loop"
data-bind="css : {selected :
$root.isSelected($parentContext.$parentContext.$index(),
$parentContext.$index(), $index())}">
Candidate index: <span data-bind="text: $index()"></span>
Cell index: <span data-bind="text: $parentContext.$index()"></span>
Row index: <span
data-bind="text: $parentContext.$parentContext.$index()"></span>
</div>
<!-- /ko -->
</div>
</div>
Demo JSFiddle.
来源:https://stackoverflow.com/questions/20497540/getting-index-of-grand-parent-in-a-nested-loop