Internet man
Internet man

Reputation: 1155

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.

Upvotes: 3

Views: 807

Answers (3)

tvanfosson
tvanfosson

Reputation: 532495

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

Upvotes: 6

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827466

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.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245429

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)

Upvotes: 2

Related Questions