Skip to content

Instantly share code, notes, and snippets.

@les2
Created April 24, 2013 18:53
Show Gist options
  • Select an option

  • Save les2/5454567 to your computer and use it in GitHub Desktop.

Select an option

Save les2/5454567 to your computer and use it in GitHub Desktop.
async api callback - there might be bugs
var asyncApi = asyncApi || (function(win) {
var asyncApi = function(globalName, queueName, createGlobal) {
var global = win[globalName];
if(!global && createGlobal) {
global = win[globalName] = {};
}
if(global) {
var queue = global[queueName] || [];
global[queueName] = {
push: function(callback) {
// immediately invoke the callback
callback.call({});
}
};
// execute any waiting callback
for(var i = 0; i < queue.length; i++) {
try {
queue[i].call({});
} catch(err) { /* ignored */ }
}
}
};
return asyncApi;
})(window);
// Example:
asyncApi('monetajs', 'cmd', false);
@les2
Copy link
Copy Markdown
Author

les2 commented Apr 24, 2013

// This code is running before API loads:
var theApi = theApi || {}; theApi.q = theApi.q || [];
theApi.q.push( function() { alert('the api is loaded - now i can use it'); });

// ... finally, the api is loaded, so it runs this code:
asyncApi('theApi', 'q'); // the alert will show now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment