Monitoring Ajax with Trinidad

One of the “patterns” in Ajax-land is to *notify* the user, that something has changed or is still ongoing, like fetching big data from the server.

Apache MyFaces Trinidad has a component (statusIndicator), that shows if a XHR (XmlHttpRequest) is still on going or not. Nice! But, Trinidad has more to offer. It lets you write custom JavaScript to monitor an Ajax request, using a state change listener.

Imagine a button to cause a (heavy) transaction like:

<tr:commandButton text="Fetch updates" partialSubmit="true"
  onclick="addListener();" .../>

The addListener() queues the custom listener:

function addListener()
{
  var requestQueue = TrPage.getInstance().getRequestQueue();
  requestQueue.addStateChangeListener(loader);
}

This function is pretty easy, it just ads the loader() function to Trinidad’s RequestQueue object. Let’s look at the loader() function itself:

function loader(state)
{
  var busy = state == TrRequestQueue.STATE_BUSY;
  var div = document.getElementById("load");
  div.style.display = busy ? "inline" : "none";
  if(!busy)
  {
    TrPage.getInstance().getRequestQueue()
    .removeStateChangeListener(loader);
  }
}

The loader() function takes one parameter (state), which will be either TrRequestQueue.STATE_READY or TrRequestQueue.STATE_BUSY, depending on the current state of the request queue. The function checks the current state and loads a (currently) hidden <div> HTML element. If the request is ongoing (the state is busy), we display the <div> element. When the request is done, the loader() function hides the <div> as well, and we remove the loader() function from the RequestQueue object, since we want to show the <div> only for this particular call.

The <div> element itself can be very simple like this one:

<div id="load"
style="display: none; background-color: red; font-size: large; width: 130px; position: absolute">

LOADING...

</div>

Have fun!

Howdy!

Posted in ajax, apache, jsf, myfaces, trinidad, web²

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: