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:

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:

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: