我正在做Knockout.js教程(教程:单页应用程序,第2步),我有一些问题需要理解。也许首先是一些代码:
查看:
<!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
<li data-bind="text: $data,
css: { selected: $data == $root.chosenFolderId() },
click: $root.goToFolder"></li>
</ul>
<!-- 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>
VieModel:
function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
self.chosenFolderData = ko.observable();
// Behaviours
self.goToFolder = function(folder) {
self.chosenFolderId(folder);
$.get('/mail', { folder: folder }, self.chosenFolderData);
};
// Show inbox by default
self.goToFolder('Inbox'); };
ko.applyBindings(new WebmailViewModel());
上面的代码片段正常工作,并显示了电子邮件列表。现在我的问题是:当我摆脱表格标签中的 data-bind =&#34; with selectedFolderData&#34; 时,我怎样才能正确地迭代邮件?我尝试将 data-bind =&#34; foreach:mails&#34; 更改为 data-bind =&#34; foreach:selectedFolderData()。邮件&#34; 但它没有用。这很奇怪,因为我能够通过以下方式获得第一封邮件的数据:
data-bind =&#34; text:chosenFolderData()。mails [0] .to&#34;
这是ajax回应:
Object {id: "Inbox", mails: Array[12]}
任何?