0

Is there a way to fire a function when another function has completed in a manner that is similar to DOM events?

e.g. (I know it's not possible but...)

$('body').on('myFunction', function(){
    alert('My function was called.');
})
1
  • I don't see your full code, but why not call the 2nd function at the end of the first one? Commented Jul 20, 2013 at 8:01

2 Answers 2

3

No, there is absolute no way to do that unless you can replace the function (i.e. have access to its scope).

If you do have access to the scope it becomes very easy though and does not need any jQuery at all:

var origFunc = theFunction;
theFunction = function() {
    var args = Array.prototype.slice.call(arguments);
    // run before the call
    var rv = origFunc.apply(this, args);
    // run after the call
    return rv;
};

See MDN for information about the arguments object containing the arguments passed to the function. Using slice to convert it to a plain array is unfortunately necessary since browsers such as IE9 fail to follow the ES5 standard properly which requires apply to accept any array-like object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It does have global scope and your example works perfectly :D
0

Not sure if this is completely what you want. But I think you should give a try to jquery Deferred objects. Have a look at the jquery documentation here - Jquery Deferred Object.

A brief overview -

  • You can specify callbacks for done/fail/always events of a deferred object.
  • All you now need to do is call the resolve/reject events on this deferred object.
  • Triggering this event will run the method specified in corresponding call back.

I have compiled this little fiddle as a demo. - FIDDLE.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.