I’m starting learn some web programming and picked up knockout.js because the MVVM pattern is familiar to me having some experience with MVVM in .Net.
But I’m having some trouble making loops with nested arrays. The model is very simple: I have an array of topics each having an array of stories.
You can check the full code on Fiddle, but here is a simplified version:
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 -->
The problem I keep getting is in the stories loop. I keep getting Message: ReferenceError: summary is not defined; but I debugged the code in Chrome and stories is indeed an array of objects with property summary defined.
What am I doing wrong here?
When you put elements inside of a
trthat are not inside of a cell, then browsers will conveniently move them outside for you where they are getting bound against the overall view model.So, you just need to ensure that your elements are inside of cells like:
Here is an update to your fiddle: http://jsfiddle.net/rniemeyer/QCY4r/1/