Thursday, August 12, 2010

Custom Ajax Callback Arguments for jQuery

I had the need to pass a custom argument to a callback function upon a successful Ajax call today.  Using jQuery for my current project I needed to find the standard way to pass custom arguments.  The API didn't list anything so I turned to Google.  Google 'suggested' using closures.  The solution would look like this:
function myCallback(o, arg) {
  // do stuff with the custom argument
  alert(arg);
}

$.ajax({
  url: 'myproxy.html',
  success: function (o) {
    myCallback(o, 'myvalue');
  }
});

What occurs above is that when the success callback function is called it passes the object returned from the asynchronous call, as well as the custom value which is explicitly defined to the inner function.  It works, but I'm not entirely happy with it.

After reviewing the jQuery API docs I decided to use the context attribute instead.  Seems slightly less kludgy to me.  It looks like this:
function myCallback(o) {
  // do stuff with the custom argument
  alert(this.myVar);
}

$.ajax({
  url: 'myproxy.html',
  success: myCallback,
  context: {myVar: 'my value'}
  }
});

Whatever is passed into 'context' becomes the context of the callback function.  This is meant to be used to pass an actual context, such as the entire document or an element within the document.  This is still pretty hacky.  What I would prefer is the type of behavior YUI has, which allows an additional attribute to be passed with the asynchronous object, which is then passed through to the callback automatically:
function myCallback(o) {
  alert(o.argument.myVar);
}

var callback = {
  success: myCallback,
  argument: {myVar: 'my value')}
}

YUI.util.Connect.asyncRequest('GET', 'myproxy.html', callback);
In perusing the jQuery source, it seems pretty easy to add this functionality.  I'm new to jQuery so I'm not sure how forks and such occur.  Is there an easier method?

1 comment:

  1. I would like to place this heart here, as a sign of my thankfulness.

    <3

    ReplyDelete