views:

198

answers:

3

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.

+1  A: 

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)

Justin Niessner
Do this with jQuery long enough and you'll find that losing the context (this) will become a real problem.
tvanfosson
+5  A: 

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 some other stuff...

      if (callback) callback.apply(this);
  }
tvanfosson
+1  A: 

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.
CMS