AJAX Callbacks and Function Closures
Working with JavaScript closures in an asynchronous context (callbacks) was a memorable experience when I first wrote the code for course links. Now I had a chance to look at it again after restoring the functionality during a recent bugfix.
A look under the hood of the fourth nested AJAX call:
- postCORS is a function that provides cross browser cross origin POST requests. XDomain request is used for IE, while the usual jQuery.post is used for othe browsers.
- because each callback needs to have an associated site dictionary from the previous callback, they need to have their own scope. Otherwise, a global variable would be overwritten each time through the loop in the parent closure.
- g simply returns whatever is passed to it. This is one way of creating an independent scope. A related way is to call new on a function that is a constructor.