JavaScript and callback nesting
- by Jake King
A lot of JavaScript libraries (notably jQuery) use chaining, which allows the reduction of this:
var foo = $(".foo");
foo.stop();
foo.show();
foo.animate({ top: 0 });
to this:
$(".foo").stop().show().animate({ top: 0 });
With proper formatting, I think this is quite a nice syntactic capability. However, I often see a pattern which I don't particularly like, but appears to be a necessary evil in non-blocking models. This is the ever-present nesting of callback functions:
$(".foo").animate({
top: 0,
}, {
callback: function () {
$.ajax({
url: 'ajax.php',
}, {
callback: function () { ... }
});
}
});
And it never ends. Even though I love the ease non-blocking models provide, I hate the odd nesting of function literals it forces upon the programmer.
I'm interesting in writing a small JS library as an exercise, and I'd love to find a better way to do this, but I don't know how it could be done without feeling hacky. Are there any projects out there that have resolved this problem before? And if not, what are the alternatives to this ugly, meaningless code structure?