[英]Nested loops in knockout.js
我開始學習一些Web編程,並學習了基因敲除(knockout.js),因為我對MVVM模式很熟悉,對.Net中的MVVM有一定的經驗。
但是我在使用嵌套數組進行循環時遇到了一些麻煩。 該模型非常簡單:我有一系列主題,每個主題都有一系列故事。
您可以在Fiddle上查看完整的代碼,但這是簡化的版本:
ViewModel.js:
function Story(t, u, v) {
var self = this;
self.summary = ko.observable(t);
self.url = ko.observable(u);
self.up_votes = ko.observable(v);
}
function Topic(t) {
var self = this;
self.title = ko.observable(t);
self.stories = ko.observableArray();
}
function TopicListViewModel() {
var self = this;
self.topics = ko.observableArray([]);
}
topic.html:
<!-- ko foreach: topics -->
<div class="span2">
<table cellpadding="2" cellspacing="2" style="width:100%" class="table">
<thead>
<tr>
<th>
<span data-bind="text: title"> </span>
</th>
</tr>
</thead>
<tbody data-bind="foreach: $data.stories">
<tr>
<!--<a data-bind="attrib: { href: url, title: summary} "></a>-->
<span data-bind="text: summary"> </span>
</tr>
</tbody>
</table>
</div>
<!-- /ko -->
我一直遇到的問題是故事循環。 我不斷收到Message: ReferenceError: summary is not defined;
但是我在Chrome中調試了代碼,並且故事確實是一組定義了屬性summary
的對象。
我在這里做錯了什么?
當您將元素放置在單元格之外的tr
內時,瀏覽器會方便地將它們移到外部,從而使它們與整體視圖模型綁定在一起。
因此,您只需要確保您的元素位於單元格之內即可,例如:
<tr>
<td>
<a data-bind="attrib: { href: url, title: summary} "></a>
<span data-bind="text: summary"> </span>
</td>
</tr>
這是您的小提琴的更新: http : //jsfiddle.net/rniemeyer/QCY4r/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.