How do I write a jquery function that accepts a callback as a parameter

sjors miltenburg picture sjors miltenburg · Jun 23, 2009 · Viewed 88.8k times · Source

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 to be able to call it like this

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

How can I implement support for callbacks in my function?

Answer

Tomalak picture Tomalak · Jun 23, 2009
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 in a callback function is straight-forward, you even do it yourself in the $.post() call.

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