Maintaining Context in Asynchronous Ajax Calls

by Dave Carroll on January 11, 2007 at 12:27 PM

Managing context during the execution of a callback function froam an asynchronous Javascript call can get a bit hairy at times.  This is because when you execute your Apex AJAX method you can only specify the function that gets called without arguments.  One example would be to pass an element to the callback that will display the data returned from the function.  Perhaps I have two tables that I would like to render asynchronously and the only difference is the destination of the data.  What would be optimal is to be able to pass the table element to my callback function, thereby avoiding duplicate code from having to similar callbacks that only differ by name.

This is possible in the new Ajax Toolkit for Winter07.  The callback argument can be a structure that contains multiple useful values.  The one that will help us in this case is the "source" value.  Our source value is essentially a set of key-value pairs.  When used as part of the callback argument, this source structure is passed, without modification, to the callback function.

Here is a sample.  In the new toolkit, you can specify a callback for failure and for success.  In either case, the "source" value is returned to our callback.  The result contains the results of the API call.

  var result = sforce.connection.query("Select Name,Id from User", {

      onSuccess : renderUser,

      onFailure : handleError,

      
source : {tableName : document.getElementById("leftUserTable"), background : "red"}
    });

  function renderUser(result, source) {
    log(source.newValue);
    var records = result.getArray("records"); 

    for (var i=0; i<records.length; i++) {
      var record = records[i];
      log(record.Name + " -- " + record.Id);
    }
  } 

  function handlerError(error, source) {
    log("oops something went wrong " + error);
  }


 

Hopefully, using the new callback structure and, in particular, the source value will ease the transition into asynchronous Javascript development.

Cheers

 

TrackBack

TrackBack URL for this entry: http://www.typepad.com/services/trackback/6a00d8341cded353ef00d8353c01f853ef

Listed below are links to weblogs that reference Maintaining Context in Asynchronous Ajax Calls:

Post a comment

If you have a TypeKey or TypePad account, please Sign In