Knockout 'for' binding?

Zholen picture Zholen · Apr 18, 2013 · Viewed 9.8k times · Source

Original Question

Does any one have or know of a binding for knockout that would allow behavior similar to a for loop? I can make a foreach do what I want but it would be nice if I didn't have to do it that way.

Edit 2

I am trying to create table rows based on a selection the user makes. In some cases I need x rows where x is the length of an array, other times x represents the largest number rows that will be needed to display n number of arrays.

Ex: image1 is built based on 4 different arrays all which vary in size image2 is built from the same array and is doubled in this case.

enter image description here enter image description here

<div data-bind="if: selectedTab()">
<table>
<thead>
  <tr>
    <td>
      <div class="a-i-post-All"></div>
    </td>
    <!-- ko foreach:$root.selectedTab().races-->
    <td>
      <input type="checkbox" />
    </td>
    <!-- /ko -->
  </tr>
</thead>
<tbody data-bind="foreach: selectedTab().runners"> // <-- This is an empty array created by the max number of Runners in the selectedTabs array of Races
  <tr>
    <td>
      <div class="a-i-post"></div>
    </td>
    <!-- ko foreach:$root.selectedTab().races-->
    <td>
      <!-- ko if: Runners.length > $parentContext.$index()-->
      <input type="checkbox" />
      <!-- /ko -->
    </td>
    <!-- /ko -->
  </tr>
</tbody>

The above works fine and creates what i want, but i don't like having to turn selectedTab.runners from a number into an empty array just to make it loop n times to create the rows. I am open for suggestions. Note As of the time I posted this question originally I have revised this code considerably and am now down to only one occurrence related to my initial question.

Answer

Michael Best picture Michael Best · Apr 19, 2013

My Repeat binding does exactly this.

<tbody>
  <tr data-bind="repeat: { foreach: selectedTab().runners, index: '$runner' }">
    <td>
      <div class="a-i-post"></div>
    </td>
    <td data-bind="repeat: selectedTab().races">
      <!-- ko if: $item().Runners.length > $runner -->
      <input type="checkbox" />
      <!-- /ko -->
    </td>
  </tr>
</tbody>