Wednesday, 22 July 2020

JET - using busy-context for custom components

JET - v7.2.0
Source: GitHub

This article demonstrates the power of JET's busy context concept. The busy context API provides the developer with an elegant way to check if a custom web component has been completely loaded into the DOM and is READY to perform its duties.

To illustrate this feature, I have a sample application, which has two custom components: user-component-one and user-component-two. On the click of a button, I populate an knockout observable-array variable with some metadata which loads both these components twice.

Here is my page, and my corresponding metadata:



As I am looping through my array, I am also interested to access a method from each of the components. And this is where I have my problem!

As soon as I try to access a method on the web components, while they are still being loaded, I get the following error:


Cannot access methods before element is upgraded - the error essentially means that until the web component is ready, you may not access any of its methods.

Fair enough!. Then how do we know that it is ready? This is where busy-context comes to our rescue. Using the busy-context API, we get back a promise which is resolved only when the web component is ready for action, or more importantly, is no more busy.

For each of the components we wish to load through our metadata, we grab its busy-context and wait for it to be free! In my case, since I have multiple components to load, I push each of these promises into an array and then resolve them all at once using Promise.all.


Once the promises are resolved, I know that these components are ready and I am able to access the getValue method.


Cheers!

No comments:

Post a Comment