> function getData(url) { > var storedData; > return function(callback) { > if (storedData) callback(storedData) > else $.getJSON(url, function(data) { > storedData = data; > callback(storedData); > }); > }; > };
That has the disadvantage that is will make the AJAX call multiple times if multiple calls come in to the generated function before the first one completes. This has the same API, but is cleaner: function getData(url) { var storedData, callbacks = []; $.getJSON(url, function(data) { storedData = data; for (var i = 0; i < callbacks.length; i++) { callbacks[i](data); } }); return function(callback) { if (storedData) callback(storedData) else callbacks.push(callback); }; }; This could easily be extended for multiple re-tries on ajax failure. But any of these techniques turn what you would like to think of as synchronous calls into asynchronous ones. A different technique avoids making you think about this, although it is equally asynchronous: Simply move your click binding inside the initial .getJSON callback. "data" will be available, and you won't have to make additional calls. The biggest disadvantage of this is that the default action will happen on your links if they're clicked before the ajax call returns. Anyway, here's a few ideas. -- Scott