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