简体   繁体   中英

Nested loops in knockout.js

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 tr that 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:

<tr>
    <td>
       <a data-bind="attrib: { href: url, title: summary} "></a>
       <span data-bind="text: summary"> </span>
    </td>
</tr>

Here is an update to your fiddle: http://jsfiddle.net/rniemeyer/QCY4r/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM