knockout 2, nested foreach

3,163 views
Skip to first unread message

Lucius Vorenus

unread,
Jan 17, 2012, 5:43:38 AM1/17/12
to KnockoutJS
Any examples of nested foreach binding? This is doesnt work

function ProgramViewModel() {
this.Trainings = ko.observableArray([new Training("training 1"),
new Training("training 2"), new Training("training 1")]);
}

function Training(name) {
this.Name = name;
this.Exercises = ko.observableArray([new Exercise("one"), new
Exercise("two"), new Exercise("three")]);
}

function Exercise(name) {
this.Name = name;
}

ko.applyBindings(new ProgramViewModel());



<ul data-bind="foreach: Trainings">
<li data-bind="text: $data.Name">
<ul data-bind="foreach: $data.Exercises">
<li data-bind="text: Name"></li>
</ul>
</li>
</ul>

mcoolin

unread,
Jan 17, 2012, 7:09:45 AM1/17/12
to knock...@googlegroups.com

Lucius Vorenus

unread,
Jan 17, 2012, 8:26:33 AM1/17/12
to KnockoutJS
thx, but my example doesnt. What im doing wrong?
Message has been deleted

Koviko

unread,
Jan 17, 2012, 9:02:22 AM1/17/12
to knock...@googlegroups.com
Firstly, you don't need to use "$data," as it is implied. Secondly, you are overwriting your list with a text binding. I assume what you meant is this:

<ul data-bind="foreach: Trainings"> 
  <li>
    <span data-bind="text: Name"></span>
    <ul data-bind="foreach: Exercises"> 

Lucius Vorenus

unread,
Jan 18, 2012, 2:41:40 AM1/18/12
to KnockoutJS
what does it mean "overwriting your list with a text binding"?

JohnEarles

unread,
Jan 18, 2012, 6:01:46 AM1/18/12
to KnockoutJS
>> what does it mean "overwriting your list with a text binding"?

Your HTML was this:

<li data-bind="text: $data.Name">
<ul data-bind="foreach: $data.Exercises">
<li data-bind="text: Name"></li>
</ul>
</li>

The top binding (<li data-bind="text: $data.Name">) is telling
Knockout to set the innerText (or textContent) for your outer li
element. This text replaces everything in between the starting and
ending tag, so it results in: <li>$data.Name</li> - overwriting your
<ul> elements HTML with the Name text.

Lucius Vorenus

unread,
Jan 18, 2012, 6:30:02 AM1/18/12
to KnockoutJS
got it! Thank you very much guys!
Reply all
Reply to author
Forward
0 new messages