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?
Best Answer
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:
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:
In this example, the code nesting follows the logical structure quite nicely.