JavaScript toolkits like jQuery are all about callback functions, and those callbacks are frequently defined anonymously. Example: Some webpage shows a list of messages in a table. To update this table, it might first ask the server for a list of all current messages (as IDs), then retrieve the content for the yet-unknown message IDs:
function fnUpdateMessages() {
$.ajax({
type: 'POST',
data: { action: 'get_message_ids' },
success: function(sData) {
var aMessageIds = sData.split(/,/);
var aUnknownIds = fnWhichIdsAreNotInTable(aMessageIds);
$.ajax({
type: 'POST',
data: {
action: 'get_message_contents',
ids: aUnknownIds.join(',')
},
success: function(oData) {
for (var id in oData.messages) {
fnInsertMessage(oData.messages[id]);
}
}
);
}
);
}
You see where I'm going? This code is ugly, since indentation is at level 6 after only 2 subsequent AJAX calls. I can of course split the anonymous functions into separate functions at the file scope, but that usually pollutes the namespace (unless one clutters stuff further by wrapping this in another anonymous function call) and it breaks the strong bond between these functions: The callbacks should really not be used by themselves; they're just like the second and third part of the original fnUpdateMessages
function.
What I'd much rather want is something like this:
function fnUpdateMessages() {
$.ajax({
type: 'POST',
data: { action: 'get_message_ids' },
success: continue(sData)
});
var aMessageIds = sData.split(/,/);
var aUnknownIds = fnWhichIdsAreNotInTable(aMessageIds);
$.ajax({
type: 'POST',
data: {
action: 'get_message_contents',
ids: aUnknownIds.join(',')
},
success: continue(oData)
);
for (var id in oData.messages) {
fnInsertMessage(oData.messages[id]);
}
}
This snippet introduces new hypothetical syntax continue(var1, var2, [...])
which defines an anonymous callback function whose body is everything that follows in the enclosing function scope. This makes those callback functions appear like synchronous code. That would have to be preprocessed, obviously, since it's not standard JS.
Before I even consider writing such a preprocessor, I would like to know if something like this already exists?
P.S. If you like this idea, please steal it. I can't quite afford yet another project at the moment. A link to your repository in a comment would be great, should you get to some working code.