Wednesday, August 7, 2013

Asynchronous JS the easy way



The objective:
To be able to call MyWidget.redraw(onRedrawCallback,...) without worrying about the previous (initialization) state of our MyWidget instance.

The code:

  1 MyWidget = {
  2     template : false,
  3     myPreciousData : false,
  4     ...
  5     __load_template : function (url, dstVar, callback, callbackArgs)
  6     {
  7         ...
  8         onResponse : function (...) {
  9             if (callback) { callback(callbackArgs); }
 10         }
 11     },
 12     ...
 13     __get_data : function (callback, callbackArgs)
 14     {
 15         ...
 16         onResponse : function (...) {
 17             if (callback) { callback(callbackArgs); }
 18         }
 19     },
 20     ...
 21     redraw : function(callback, callbackArgs)
 22     {
 23         if (!MyWidget.template){
 24             MyWidget.__load_template( MY_TEMPLATE_URL , MyWidget.template, MyWidget.redraw /*"recursive*/ );
 25             return;
 26         }
 27         if (!MyWidget.myPreciousData){
 28             MyWidget.__get_data(MyWidget.redraw /*callback to our own function */, false, false);

 29             return;
 30         }
 31         if (! document.getElementById("myContainer") {
 32             MyWidget.__setUpContaier(MyWidget.redraw);

 33             return;
 34         }

 35         /* At this point all Object data (template, myPreciousData, container,...)
 36          * has been initialized. */
 37         ...
 38         if (callback) { callback(callbackArgs); }

 39     }...
 40 }
 41
 42 var postRedrawFunct = function (...) {
 43 }
 44
 45 }
 46 myGUIElment.onClick(MyWidget.redraw(postRedrawFunct, ...)); // Just call redraw.

No comments: