How to write a jquery function that takes a callback as a parameter

I have the following function.

function ChangeDasPanel(controllerPath, postParams) { $.post(controllerPath, postParams, function(returnValue) { $('#DasSpace').hide("slide", { direction: "right" }, 1000, function() { $('#DasSpace').contents().remove(); $('#DasSpace').append(returnValue).css("display", "block"); $('#DasSpace').show("slide", { direction: "right" }, 1000); }); }); }; 

But I want it to be called that

 ChangeDasPanel("../Home/Test", {} ,function (){ //do some stuff on callback } 

How can I implement callback support in my function?

+48
javascript function jquery callback
Jun 23 '09 at 10:07
source share
4 answers
 function ChangeDasPanel(controllerPath, postParams, f) { $.get( controllerPath, postParams, function(returnValue) { var $DasSpace = $('#DasSpace'); $DasSpace.hide( "slide", { direction: "right" }, 1000, function() { $DasSpace.contents().remove(); $DasSpace.append(returnValue).css("display", "block"); $DasSpace.show("slide", { direction: "right" }, 1000); } ); if (typeof f == "function") f(); else alert('meh'); } ); }; 

You can pass functions like any other object in JavaScript. Passing the callback function is straightforward, you even do it yourself in the $.post() call.

You can decide whether you want your callback to be called as part of the $.post() callback or on its own.

+74
Jun 23 '09 at 10:18
source share

You know that global variables and functions are evil, so don't put them in the jQuery namespace:

 $.extend({ myFunc : function(someArg, callbackFnk){ var url = "http://example.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 }); 

Read this post for a better understanding: Creating jQuery callback functions

+22
Feb 26 '10 at 20:15
source share

If I understand you correctly, it is as simple as setting another parameter and calling the variable as a function:

 function foo(mycallback) { mycallback(); } 
+14
Jun 23 '09 at 10:31
source share

Why don't you use an object that you can pass to functions. This is much more like jQuery, and it saves you from having x-named parameters that are hard to maintain, as they can become cumbersome when you get 3 parameters.

eg

 function callingFunction(){ var fnSettings: { url: someUrl, data: params, callback : function(){} }; yourFunction( fnSettings ); } function yourFunction( settings ) { $.post( settings.url, settings.data, settings.callback ); } 
+11
Jun 23 '09 at 10:42
source share



All Articles