views:

786

answers:

3

I'm building a concert calendar that's very heavy on javascript (using jQuery). I'm having trouble synchronizing various events throughout the app, and I'm looking for suggestions for how to do this.

An example of a simple use case:

  1. User clicks a month
  2. Calendar skips to that month

An example of a more complex use case:

  1. User selects an artist
  2. Calendar determines the date of that artist's first show
  3. Calendar skips to that month
  4. Calendar highlights that artist's show(s)

One occasional problem is that the new month isn't yet rendered by the time I try to highlight the artist's show(s). Thus, the show isn't highlighted even though these functions are called in order. Obviously, using setTimeout() is pretty hacky, and not guaranteed to work.

So first, a simple question -- would it ever be possible (even in Chrome) for the following function to run out of sequence?

function steps(){

    stepOne(); //TAKES 30 SECONDS

    stepTwo(); //TAKES < 1 SECOND

}

Second, a related simple question:

    If placed at the end of a function, will a JS callback ALWAYS run after 
    everything else in the given function has finished running?

If so, I could nest each function as a callback of its previous function. But that would likely become unwieldy, once you consider all the different use cases.

Here's an approach I'm considering:

    1) Allow each function an optional callback parameter. If it's present,
       call it at the very end of the function.

    2) During a UI refresh, create an array, and stack any functions to be
       called within this array.

    3) Once this "script" is completed, iterate through the array, calling
       each function in the order it was added, using the next function 
       as the previous function's callback.

I imagine this would ensure that all the functions are called in order.

Another approach is to attach event listeners using

$(document).bind("listener.name", fnCallback);

And then calling

$(document).trigger("listener.name");

Whenever that event occurs.

However, I'm guessing this would be kind of unwieldy as well, considering different events might need to call different sets of functions depending on the use case. I could always call

$(document).unbind("listener.name");

before adding new events to it, but again -- I'm leaning toward creating sort of a master "script" as I suggested in the first approach.

Hopefully this isn't too vague -- any feedback? Any experience with complex UIs that had to synchronize various events?

Thanks very much,

Michael

A: 

Try passing in the function to be called back to as an argument

function steps(){

    stepOne(stepTwo); 

}

function stepOne(callback){

    var AsyncDone = function() { 
      //any Synchronus Things here
      callback(); 
    }
    someAsyncFunction( params, AsyncDone );

}
A: 

Your approach #1 is the best way, and the most natural using jQuery. Most functions that act on the user interface and do something accept a callback function parameter, which gets called after the function has executed.

Where you are doing things not implemented in jQuery following the same pattern will make your code more readable. dominic's answer is a good terse example:

function steps(){

    stepOne(stepTwo); 

}

function stepOne(callback){

    var AsyncDone = function() { 
      //any Synchronus Things here
      callback(); 
    }
    someAsyncFunction( params, AsyncDone );

}
Adam
I think this is a good point that it follows jQuery convention. However, I've found that there are some times when setting a timeout of 1ms will make things work where they didn't before. That doesn't make any sense to me (if JS calls are truly executed in order -- minus asynchronous calls, of course), but it's a hack I'll have to live with for now. Thanks, everyone -- all advice very much appreciated :)
kaneuniversal
+1  A: 

The last approach, of using custom events, is the best approach in my humble opinion.

Design various components and events and let them interact with each other.

E.g. Let's say you have a Calendar object.

var calendar = function()
{
     var pub = {};


     pub.highlightRow = function(row) {};

     pub.getRowByContent = function(content) { };

     pub.selectMonth = function()
                       {
                            //your code to actually select month.

                            //Once all the necessary DOM work is done, fire the
                            //monthSelected event (namespacing the event so as to avoid the clash with other events). 
                            $(document).trigger('calendar:monthSelected');
                        };

     return pub;
}();

Now your artist search method may look like,

function searchArtist(artistName)
{
    $(document).bind('calendar:monthSelected'), function()
                                                {
                                                    calendar.highlightRow(calendar.getRowByContent(artistName));
                                                }
                                                );

    calendar.selectMonth(getShowMonthByArtist(artistName));
}
SolutionYogi