3

I've been going through the learn.knockout.js tutorials and been experimenting. Can someone explain why this works [Tutorial: Single page applications, Step 2] (using with: chosenFolderData and foreach: mails):

<!-- Mails grid -->
<table class="mails" data-bind="with: chosenFolderData">
    <thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
    <tbody data-bind="foreach: mails">
        <tr>
            <td data-bind="text: from"></td>
            <td data-bind="text: to"></td>
            <td data-bind="text: subject"></td>
            <td data-bind="text: date"></td>
        </tr>     
    </tbody>
</table>

but not this (using just foreach: chosenFolderData.mails):

<!-- Mails grid -->
<table class="mails">
    <thead><tr><th>From</th><th>To</th><th>Subject</th><th>Date</th></tr></thead>
    <tbody data-bind="foreach: chosenFolderData.mails">
        <tr>
            <td data-bind="text: from"></td>
            <td data-bind="text: to"></td>
            <td data-bind="text: subject"></td>
            <td data-bind="text: date"></td>
        </tr>     
    </tbody>
</table>

I suspect it's because while chosenFolderData is observable, chosenFolderData.mails is not. Can anyone tell me for certain?

Many thanks!

-- Ralph

Charles
  • 50,943
  • 13
  • 104
  • 142
Rafe
  • 5,237
  • 3
  • 23
  • 26

1 Answers1

6

Because you are not actually accessing the property you want with the way it is written. In the model chosenFolderData is an observable and must be called like a method to retrieve the value. To provide the functionality without using with (and I suggest not using with where high performance is necessary because of the overhead)...

<tbody data-bind="foreach: chosenFolderData().mails">
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • @Quintin Robinson - Just so you know, Quintin, I have quoted part of your answer in a question I have just posted: http://stackoverflow.com/questions/9927213/performance-tuning-a-knockout-application-guidelines-for-improving-resposne-ti – Mark Robinson Mar 29 '12 at 14:19