Knockout.js foreach afterRender when loop is completed

K

I have been using Knockout.js’s afterRender for years to hide a progress bar when the foreach loop completed. All of those years I have been using it incorrectly. Once I read Knockout’s documentation about the foreach data binding function, I realized that it is actually called after each render of the element inside the foreach. This is definitely not how I wanted this function to work. In this Knockout.js tutorial let me show you my solution to accomplish applying the afterRender when the foreach has completed.

Understanding the foreach afterRender

Knockout’s documentation is quite clear:

afterRender — is invoked each time the foreach block is duplicated and inserted into the document, both when foreach first initializes, and when new entries are added to the associated JavaScript array later. Knockout will supply the following parameters to your callback

Given that Knockout has multiple events I expected something like a onComplete or some other appropriately named event. Unfortunately there is not. Time to explore my solution.

Implementing your own afterRender

The previous way I would implement a foreach with afterRender was as follows:

[code]
<!– ko template: { foreach: pagingService.entities, afterRender: pagingService.hideProgressBar } –>

<!– /ko –>
[/code]

After each entity was drawn my hideProgressBar function was called. Luckily the loop is extremely fast so the user does not notice the prematurely hiding of the progress bar. I think this foreach template has a good possibility to be converted into a Knockout.js component similar to the one I created with a check/uncheck all tutorial.

Enter my solution:

[code]
<!– ko template: { afterRender: pagingService.hideProgressBar } –>

<!– ko foreach: pagingService.entities –>

<!– /ko –>

<!– /ko –>
[/code]

As you can see, the solution is to remove the afterRender from the foreach to a standard template binding.

Boom, hideProgressBar is only called at the end of the foreach loop.

Other useful articles

About the author

By Jamie

My Books