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

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:


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

Published on Apr 3, 2019

Tags: foreach | Knockout js Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.