Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting $index of grand parent in a nested loop

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

like image 463
Suwer Avatar asked Dec 10 '13 14:12

Suwer


1 Answers

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.

like image 71
nemesv Avatar answered Nov 19 '22 17:11

nemesv