1

I have a function containing a callback that I want to optionally relay back to the original function call when it is complete... If that makes sense.

e.g.:

const UI = {
    update : function(var1) {
        $(var1).animate({ opacity: 0 }, 100, "linear", function() {
                // Callback 1: Do stuff
        });
    }
}

What I want is to have the following:

UI.update("whatever", function() {
   // Callback 2: Do more stuff after Callback 1 is complete
});

Is it possible to do it inline like this?

Rob
  • 14,746
  • 28
  • 47
  • 65
Microsis
  • 279
  • 1
  • 2
  • 11

1 Answers1

4

Yes, certainly — just declare a parameter for the callback, and then if update doesn't have to do anything when the animation is finished, just pass the callback to animate directly:

const UI = {
    update : function(var1, callback) {
// -------------------------^
        $(var1).animate({ opacity: 0 }, 100, "linear", callback); // ***
    }
};

If update needs to do more work before calling the callback, just call the callback from within the animate callback:

const UI = {
    update : function(var1, callback) {
    // ---------------------^
        $(var1).animate({ opacity: 0 }, 100, "linear", function() {
            // ...work `update` does here...
            // Call the callback:
            if (callback) {                                           // ***
                callback(/*...perhaps some arguments here...*/);      // ***
            }                                                         // ***
        });
    }
}

It's not a problem that the call to callback won't be until after update has returned. The animate callback is a closure¹,² over var1 and callback (more accurately, over the lexical environment they exist within), so they'll remain accessible after update returns.

You may be happy with just the "truthy" check shown above. Other times, people are more rigorous, e.g.:

if (typeof callback === "function") {

(Many years ago, in web browsers some host-provided functions had "object" rather than "function" for their typeof, but all vaguely-modern browsers ensure it's "function" now.)


For more about closures:

¹ Closures are not complicated on my anemic little blog (some outdated terminology, but...)

² Canonical Stack Overflow question about closures

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Excellent. Thank you gents. @T.J.Crowder I assume any work `update` needs to do should happen before the `.animate` call anyway (unless of course it needs to be done after the animation)? – Microsis Jun 29 '19 at 16:33
  • @Microsis - It depends on what the work is, but probably, yeah. :-) – T.J. Crowder Jun 29 '19 at 17:08