【发布时间】:2012-08-04 22:22:24
【问题描述】:
我开始学习一些 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 中调试了代码,并且 stories 确实是一组具有属性 summary 定义的对象。
我在这里做错了什么?
【问题讨论】:
标签: javascript loops knockout.js nested-loops knockout-2.0