Follow @endyourif rss Facebook LinkedIn

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

Published on Apr 3, 2019

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

<!-- 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: foreach | afterrend | Knockout js Tutorial

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