Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top