Is there a way to add a callback to any given javascript function without changing its definition? Can this be done without using a library like deferred?
Javascript – Adding a callback to a function
javascript
Related Solutions
There's quite a few Javascript engines you can use. Which one makes most sense will largely depend on your specific platform/target environments/needs.
There's the V8 javascript engine that powers Chrome, and Firefox's SpiderMonkey.
If Windows-only would suffice, you can use Active Scripting (IActiveScript site and other interfaces). A number of my Windows applications do this.
If QT, I believe they have their own JavaScript classes that can be accessed.
Thats not an exhaustive list, I'm sure there are others. But that should get your search started.
Just because you can use anonymous functions (lambdas) for this kind of construct doesn't mean you have to. Just like it's good practice to pull complex value construction syntax out of a function call and into its own variable, you can do the same with your function literals. Observe:
// Your example:
$(".foo").animate({
top: 0,
}, {
callback: function () {
$.ajax({
url: 'ajax.php',
}, {
callback: function () { ... }
});
}
});
// Can be rewritten as:
var animateProps = { top: 0 };
var animateCallback = function() {
var ajaxProps = { url: 'ajax.php'; }
var ajaxCallback = function () { ... }
$.ajax(ajaxProps, {callback: ajaxCallback});
};
$(".foo").animate(animateProps, {callback: animateCallback});
// Or even, depending on what you do inside the ajax callback:
var animateProps = { top: 0 };
var ajaxProps = { url: 'ajax.php'; }
var ajaxCallback = function () { ... }
var animateCallback = function() {
$.ajax(ajaxProps, {callback: ajaxCallback});
};
$(".foo").animate(animateProps, {callback: animateCallback});
And all the ugly nested syntax is gone!
Note, however, that the nested-anonymous-function style isn't all that bad; after all, if your function calls follow a logical structure, then so will the function call nestings. Example:
doAsyncSomething(
function(successData){
alert("All is well!");
},
function(errorMessage){
alert("Oh no! Something went wrong! Namely: " + errorMessage);
});
In this example, the code nesting follows the logical structure quite nicely.
Best Answer
You can make any function have a callback in javascript using the following function:
Sample in console:
If you want the callbacks deferred, you can make the slight modification:
Sample in console:
Note that this is basically a really stupid thing to write, as you usually want to pass more interesting information to a callback than a return value, and you want the function to probably have better control over when the callback gets called. Just changing the function is probably for the best. It's also a huge waste of resources, if you care about that kind of thing.