Solution to the problem with callback function

saran | May 1 - 2010


Common problem with callbacks are parameters. You might have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:

 // get some data
 var foobar = ...;
 
 // specify handler, it needs data as a parameter
 function handler(data) {
   //...
 }
 
 // add click handler and pass foobar!
 $('a').click(function(){
   handler(foobar);
 });
 
 // if you need the context of the original handler, use apply:
 $('a').click(function(){
   handler.apply(this, [foobar]);
 });

Another alternative way for this will be using the JSONP padding

  • jQuery supports JSONP (‘JSON with padding’) which effectively means you can make cross-domain “Ajax” requests (This doesn’t use XHR).
  • For this to work the requested domain must have some JSONP API in place (it must be able wrap the JSON with a specified callback function). An example:
function getLatestyoutubePics(tag,callback) {
    var youtubeFeed = 'http://api.youtube.com/services/feeds/photos_public.gne?tags='
                   + tag + '&tagmode=any&format=json&jsoncallback=?';
    jQuery.getJSON(youtubeFeed, callback);
}
 
// Usage:
getLatestyoutubePics('ferrari', function(data){
    jQuery.each(data.items, function(i, item){
        $("<img/>").attr("src", item.media.m).appendTo('body');
    });
});
  • You might find it a little messy but jQuery enables us to create an entire DOM structure within a single chain:
// Create and inject in one chain:
jQuery('<div/>')
    .append('<p><a href="#">Foo</a></p>')
    .find('p a')
        .click(function(){
            // Do something...
            return false;
        })
        .end()
    .append('<p><a href="#">Bar</a></p>')
    .find('p:eq(1) a')
        .click(function(){
            // Do something else...
            return false;
        })
        .end()
    .appendTo('body');