I have a simple observableArray which contains a lot of user-models. In the markup, there is a template with a foreach loop which loops the users and outputs them in a simple table. I additionally style the table with a custom scrollbar and some other javascript. So now I have to know when the foreach loop is finished and all the models are added to the DOM.
The problem with the afterRender callback is that it gets called every time something is added, but I need kind of a callback which fires only once.
Your best bet is to use a custom binding. You can either place your custom binding after
foreach
in the list of bindings in yourdata-bind
or you could execute your code in asetTimeout
to allowforeach
to generate the content before your code is executed.Here is a sample that shows running code a single time and running code each time that your observableArray updates: http://jsfiddle.net/rniemeyer/Ampng/
HTML:
JS:
I am not sure if the accepted answer will work in knockout-3.x (as data-bindings no longer are run in the order you declare them).
Here is another option, it will only fire exactly once.
I came up with an elegent cheat. Immediately after your template / foreach block, add this code:
Just off the top of my head you could either:
Example:
Not tested this so just guessing...
Jaffa's answer has contains an error so I decided to create a new answer instead of commenting. It is not possible to use with and template at the same time. So just move your model to template's
data
tagHtml
Javascript
How about using a debouncer?