Knockout.js — understanding foreach and with

2019-07-03 19:05发布

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

1条回答
Emotional °昔
2楼-- · 2019-07-03 19:08

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">
查看更多
登录 后发表回答