knockout.js with nested foreach loop

2019-03-31 19:00发布

问题:

I am working with knockout.js 2.0 and when i do a nested foreach loop the performance is extremely slow. The main loop has about 70 records being returned and the array inside those 70 json records contain anywhere from 0 - 20 items. So i feel this is not alot of json data.

I am just testing with the below code:

    <table>
        <tbody data-bind="foreach: Employees, visible: Employees().length > 0">  
            <tr>                
                <td class="centerdata" data-bind="text: ID"></td>
                <td class="centerdata" data-bind="text: Name"></td>
                <td>
                   <table>
                       <tbody data-bind="foreach: $data.Transactions">  
                           <tr>   
                              <td data-bind="text:TransDate"></td>
                           </tr>
                       </tbody>
                   </table>
                </td>
            </tr>                    
        </tbody>
   </table>

The page takes about 20 seconds to load. There are other fields inside the json, but I have removed them for simplicity.

Thanks, Matt

回答1:

I think there must be something else going on here, Matthew.

I have knocked up a quick fiddle, using your markup with some dummy data of a similar size to what you mention and the performance is ~1 second in Chrome.

http://jsfiddle.net/unklefolk/DCLaR/

Is there a dependent observable that is being repeatedly calculated? If so, take a look at the throttle functionality (http://knockoutjs.com/documentation/throttle-extender.html)