开发者

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 ba开发者_StackOverflow中文版ck after success})

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

Thanks


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.
});


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");
});


function loadProjects(pID, callback) {

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

}

Invoking something like this:

loadProjects(111, function() { alert('hello!'); });


You can pass a function to another function as if it were any other object. Check this out:

function loadProjects(pId, callback) {

  $.ajax({
    url: myUrl,
    success: function() {
      callback.call(); // <-- invokes your callback with no args
    }

}

You might also read up on the MDC documentation (function.call()).


function loadProjects(pID, callback) {
  $.ajax({
    url: myURL,
    success: function (dataJS) {
      // your initial method declaration goes here
      ...

      // just call the callback method at the end of the success method
      callback();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜