简体   繁体   中英

Creating my own callbacks

I have a page with some jQuery, and a separate non-jQuery function.

Currently my function runs on $(document).ready, but I want to call a jQuery function as soon as my function is finished. I can pass my function as a callback to any jQuery function, but how can I set things up the other way round?

So I would ideally like to know how to create a function foo that will take care of this for me:

$(document).ready(function() {
  foo(myfunction(), $(bar).something);
}

or how to extend an existing function to handle callbacks. Thanks.

Define your function to accept an (optional) callback, then use the javascript call() or apply() method if the callback exists. To retain the context, pass the current value for this (or whatever context you want) to the apply method. Call() and apply() differ based on how arguments are passed.

function myfunction(callback) {
    // do stuff
    if (callback) 
        callback.apply(this);
}

All you have to do is create your custom method to accept another variable...in this case, a function reference.

If you had something like this:

var add = function(a, b){
    return a+b;
};

To add a callback, you'd change it to this:

var add = function(a, b, callback){
    callback();
    return a+b;
};

(extremely poor example, but it gets the point across)

What about function-wrapping:

Function.prototype.appendCallback = function(callback){
  var fn = this;
  return function(){
    fn.apply( this, arguments ); // execute original function
    callback.call(this);         // then the callback
  };
};

Example:

var newConfirm = window.confirm.appendCallback(function () {
  alert('after from callback');
});

newConfirm('hello?'); // shows a confirmation, and then executes the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM