简体   繁体   中英

Inline callback function within a callback?

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.

eg:

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?

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, eg:

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

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