Rafe
Rafe

Reputation: 5295

Knockout.js -- understanding foreach and with

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

Upvotes: 3

Views: 3208

Answers (1)

Quintin Robinson
Quintin Robinson

Reputation: 82355

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">

Upvotes: 6

Related Questions