0

I'm just getting started with knockout.js. I have a foreach binding like this, which works fine:

<ul data-bind="foreach: people">
   <li> .... </li>
</ul>

people is part of my model that I pass to ko.applyBindings. According to the documentation, the following should work too:

<ul data-bind="foreach: {data: people}"> 

But it does not. The list remains empty, but I don't see any error in the error window of my browser. Any hint what I might be doing wrong? Is there some subtle difference between both calls which I don't see?

My idea is to pass handlers for afterAdd to foreach. Therefore I need the second way to call it.

Achim
  • 15,415
  • 15
  • 80
  • 144
  • 2
    At first sight, it seems that it should work ok. Besides that, knockout has a big try-catch somewhere that's probably hiding the error messages (had that problem a few times), look it up in the code and set your own breakpoint, maybe that'll help you to find the issue. – julioolvr May 21 '12 at 18:27
  • The binding change shouldn't give the effect you're seeing with all other code unchanged, the behavior should be exactly the same. Did you change anything else at the same time? – Joachim Isaksson May 21 '12 at 18:32
  • This could be a lot of things, a fiddle will help a ton! – Allen Rice May 23 '12 at 00:00

2 Answers2

0

I believe you are actually looking for the template binding. Foreach is a shortcut onto it, but if you need afterAdd you could use the full binding:

<ul data-bind='template: { foreach: people,
                        afterAdd: myPostProcessingLogic }'> </ul>
Kyeotic
  • 19,697
  • 10
  • 71
  • 128
0

Just for the records: The solution is a bit strange and the source of the problem was another error in my code. people is initialized via ko.observableArray. When I got new data from the server, I udated my model like this:

model.people(ko.observableArray(newData));

Now I know that the this is the correct way to do it:

model.people(newData);

For whatever reason, the first version still works with certain template binding specifications, but not for all. The second one works fine in every case.

Achim
  • 15,415
  • 15
  • 80
  • 144