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 to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Derik Whittaker, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}