• Jul
  • 09
  • 2012

How to create callback functions for jQuery plugins & extensions?

Most of the time custom jQuery plugins and extensions that we create do not use callback functions. They usually simply work on DOM elements or do some calculations. But there are cases when we need to define our own custom callback functions for our plugins.And this is especially true when our plugins utilize AJAX querying.

Let’s say our custom jQuery extension gets data by making some AJAX request.

$.extend({ 
myFunc : function(someArg){ 
var url = "http://site.com?q=" + someArg;

$.getJSON(url, function(data){

// our function definition hardcoded

});
}
});

What is bad in this jQuery code is that the callback function is defined and hard-coded right in the plugin itself. The plugin is not really flexible and its user will have to change the plugin code, which is bad!

So the solution is to define your own custom callback function argument. Here is how it is done:

$.extend({
myFunc : function(someArg, callbackFnk){
var url = "http://site.com?q=" + someArg;
$.getJSON(url, function(data){

// now we are calling our own callback function
if(typeof callbackFnk == ‘function’){
callbackFnk.call(this, data);
}

});
}
});

$.myFunc(args, function(){
// now my function is not hardcoded
// in the plugin itself
});

The above code shows you how to create a callback function for AJAX load, but if you want to create a simple callback function for your jQuery plugin, for example, the one that executes on your own custom events. To achieve this you can do the following:

$.extend({
myFunc : function(someArg, callbackFnk){
// do something here
var data = ‘test’;

// now call a callback function
if(typeof callbackFnk == ‘function’){
callbackFnk.call(this, data);
}
}
});

$.myFunc(someArg, function(arg){
// now my function is not hardcoded
// in the plugin itself
// and arg = ‘test’
});

Need help with jQuery? We can help you.

Contact Us

Ravi Makhija

Ravi Makhija

A writer, an Entrepreneur. Curious about the internet of everything. Interested in the cutting edge landscape of mobile apps and SAAS products. Blogs for Guru Technolabs - A Mobile App Development Company.

Let's Discuss a Project

Please share your unique idea or project requirement with us, our business concern person will get back to you with further details.