Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Knockout Template and DOM access race conditions

DZone's Guide to

Knockout Template and DOM access race conditions

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

I am working on a learning project and I am using the Knockout JS template bindings along w/ the Knockout External Template engine.  Things were working as expected until I wanted to add a pager to my list. 

The issue is that the Bootstrap Paginator needs access to the underlying DOM in order to build the paging component.  However, the because the fetching of the template and the loading of the DOM are both async I was having issues because in some cases my HTML would return prior to my data and everything work as expected but in other cases my data would load first and the DOM would not be ready. 

In the cases when my DOM was not ready I would not be able to get access to the DOM element in order to have my pager built.  What I needed was a way to be notified once the DOM was loaded.  Fortunately for me template binder exposes a ‘afterRender’ method which I could use to build my pager.  Once I hooked up this afterRender correctly I was able to remove the race condition and I was happy :)

Here is my original binding setup WITHOUT the ‘afterRender’:

image

Here is my updated bindings to use the ‘afterRender’

image

Hope this helps someone.

Till next time,

P.S. If you want to learn more about Knockout watch my Pluralsight Course on Knockout JS

P.S.S. If you want to learn how to transition your XAML skills to HTML you can watch my course on Html for the XAML Developer

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}