jQuery PNG LogoI was working on my CMS (Just took a brake to write this), and I tried to figure out how to pass additional arguments to a javascript callback. After some searching I found what I was looking for, I told the people in the jQuery IRC channel and someone gave me shorter and cleaner code that does the same. So let me run you through the code (Note: This is jquery but the same method would also work with normal Javascript) .

In this example I will use an argument that defines where to load the data got from an AJAX request in.

//Custom function that's used instead of the long jQuery Syntax
function loadUrl(url, destination)
{
    // Use a get request to get the page at URL
    $.get(url, function(html, status) { loadedPage(html, status, destination) });
}

// The callback function
function loadedPage(html, status, destination)
{
    // If the AJAX call failed stop the function
    if(status != "success")
        return;

    // Set the html of destination (Which is in this case a jQuery Selector) to the jquery repsonse
    $(destination).html(html);
}

If you haven’t figured out how to pass the additional arguments from the above example I’ll explain in detail, Let’s take a closer look at line 5(Formatted for readability).

$.get(url,
    function(html, status)
    {
        loadedPage(html, status, destination)
    }
);

As you can see we are using a custom defined function for the callback, What we do is make a function that has the arguments that get passed to the callback.

function(html, status)
{

}

And in that function we call our real callback function but with the additional arguments we passed to loadUrl()

function(html, status)
{
    loadedPage(html, status, destination)
}

And that’s it, this can be done with as many additional parameters as you like just add them to the call of the real callback function.

Leave a comment if you have any questions or feedback.

Regards, Xeross