Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a jQuery function with a callback?

I have the following function:

function loadProjects(pID) {

    $.ajax({
        url: myURL,
        success: function (dataJS) {XXXXXXXXXXXXXXXX}
    });
}

I call this function like so loadProjects(1);

Issue is I want to be able to define a callBack function after success, and I'd like to include it when I do loadProjects(1, callback:{whatever js is included here gets called back after success})

How can I have a function accept a callback? How can I pass a callback to that function?

Thanks

like image 530
AnApprentice Avatar asked Apr 27 '11 00:04

AnApprentice


2 Answers

function loadProjects(pID, callbackFunction)
{
    $.ajax({
        url: myURL,
        success: function (dataJS)
        {
            if(typeof callbackFunction == 'function')
            {
                callbackFunction.call(this, dataJS);
            }
        }
    });
}

Usage:

loadProjects(pID, function(dataJS)
{
    // do stuff with your dataJS, bear in mind you can call the parameter any name.
});
like image 182
N.B. Avatar answered Nov 11 '22 20:11

N.B.


Here's how you can modify your function so that it can accept a callback.

function loadProjects(pID, callback) {
    $.ajax({
        url: myURL,
        success: function (dataJS) {
          if ($.isFunction(callback)) {
            callback.call();
          }
        }
    });
}

Here's how you would use it.

function myCoolCallback() {
  alert("I am cool");
}  

loadProjects(123, myCoolCallback);

Or you can use it with an anonymous function like so.

loadProjects(123, function() {
  alert("I am cool");
});
like image 31
jessegavin Avatar answered Nov 11 '22 20:11

jessegavin