Getting $index of grand parent in a nested loop

2019-06-15 01:08发布

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条回答
Deceive 欺骗
2楼-- · 2019-06-15 01:50

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.

查看更多
登录 后发表回答