Friday, June 8, 2018

Using callbacks to force function completion in order (jQuery)

I had a recent issue with a dynamic page constructed in SharePoint using jQuery.  The page had two functions.  The first used SPServices to extract data from a SharePoint list.  The second configured the jQuery ShowCase object to create a content slider based on the content extracted from the SharePoint list.  However, while the content initially loaded, any button or link clink would clear the content, the ShowCase went blank.

I put some alerts into the code to find out what was happening and found that, if I had an alert at the end of each function, they worked.  If I removed the alerts, it no longer worked.

What was happening here was that the alerts were giving enough time for one function to complete before the other started.  The first function would fire, the alert would come up on the screen.  This would give sufficient time for the data to return and then the ShowCase Function would fire on the completed content.  But how to do this without alerts?

The answer was jQuery callbacks.  This code forces the execution of each function in sequence, and, critically, does not fire the second function before the first has completed.  Here is what that looks like:

  var callbacks = $.Callbacks(); // create callbacks object
  callbacks.add(getData); // add the data extraction function
  callbacks.add(renderShowCase); // add the ShowCase render function; // fire those functions in sequence.

By default, javascript functions on a page load to not complete (and return data) before subsequent functions are fired.  If none of the functions are dependent on others completing, then this is the most efficient way of rendering the page.  If however one of the functions is dependent on another completing before firing, callbacks are an excellent solution.

No comments:

Post a Comment