login
jQuery home stretch posted: Wed 2013-06-26 21:00:39 tags: tech
I knew in my gut that there must be some way, if only for parsimony's sake, to pass a named function, encapsulating an AJAX call as a success/fail/always handler, to another jQuery AJAX call, rather than duplicate the same anonymous record-save function code repeatedly in various branches of the collision-detection decision tree. This was the last step to truly making jQuery's AJAX facility completely my bitch, and it boiled down to a basic JavaScript syntax review.

My hurdle was, as soon as you say something like...
myAjax = $.post("middleware.php",{data:someData});
...then JavaScript runs the jQuery object's .post() method with the given parameters, and assigns the result to the variable myAjax.

This article inspired some work-arounds, such as binding a custom event to the document object (fancy, code-intensive), or binding an anonymous function to the .change event of a DOM element and triggering it artificially with myObject.change() (both sloppy and kludgey).
$(document).bind("saveRecord", function(event) {
   $.post("middleware.php",{data:someData});
});

But actually, JavaScript uses "function" as a declaration signifier as well, so none of the chicanery of minting custom events, or twiddling the .change method of custom properties, is even necessary to define a function without invoking it:
function saveRecord(){
   $.post("middleware.php",{data:someData});
});

... or even ... var saveRecord = (function(){
   $.post("middleware.php",{data:someData});
});