Passing custom arguments to jQuery ajax callback functions
When phasing out our old collection of ajax help functions, I ran into a problem with passing custom arguments to the callback function of the ajax request. Our old ajax functions were based on eval()'ing and could accept custom arguments as a literal string that was used together with the function name to construct the call of the callback. When using jQuery, the situation is different, since jQuery provides the callback function with a fixed set of arguments:
$.get('/some/url', function(data, textStatus, XMLHttpRequest) { //do something });
or even simpler, desregarding the last two arguments
$.get('/some/url', function(data) { //do something });
or, using a non-inline function as the callback:
$.get('/some/url', myFunc); function myFunc(data) { //do something }
The solution I came across when looking for a way to pass custom arguments to the callback was to create a closure:
var myArg1 = 'test' , myArg2 = 44; $.get('/some/url', function(data) { myFunc(data, myArg1, myArg2); }); function myFunc(data, customArg1, customArg2) { //do something }
I'm not an expert on closures, but basically, variables defined in the same scope as the anonymous function will be available to the anonymous function even after the outer function has returned. So even though the call to the anonymous function, which in turn calls our "real" callback function, occurrs at a later stage, the values of our custom arguments will be those that were defined at the time of the closure being defined.

Add new comment