Helping you solve those tough coding problems!

Knockout.js foreach afterRender when loop is completed Knockout.js foreach afterRender when loop is completed

Published on Apr 3, 2019 by Jamie Munro

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 afterRender 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. 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 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:


<!-- ko template: { foreach: pagingService.entities, afterRender: pagingService.hideProgressBar } -->

<!-- /ko -->


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.

Enter my solution:


<!-- ko template: { afterRender: pagingService.hideProgressBar } -->

<!-- ko foreach: pagingService.entities -->

<!-- /ko -->

<!-- /ko -->


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.

Tags: afterrend | KnockoutJS

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP

Related Posts