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