Skip to content

Instantly share code, notes, and snippets.

@mkoryak
Created November 13, 2012 16:24
Show Gist options
  • Save mkoryak/4066748 to your computer and use it in GitHub Desktop.
Save mkoryak/4066748 to your computer and use it in GitHub Desktop.
easy to use deferred shim
//requires jQuery.Deferred
_deferred = (function(){
var that = {};
var deferred = {};
var lazy = function(name) {
if(!deferred[name]){
deferred[name] = $.Deferred();
}
return deferred[name];
};
that.resolve = function(name, arg) {
return lazy(name).resolve(arg);
};
that.resolveCallback = function(name, arg){ //version of 'resolve' that can be used as a callback
return function(){
that.resolve(name, arg);
}
};
that.done = function(name, fn) {
return $.when.apply($, _.map(_.isArray(name) ? name : [name], lazy)).done(fn);
};
return that;
}());
//usage:
google.load('maps', '3', {other_params:'sensor=false', "callback" : _deferred.resolveCallback('gmap')});
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : XXX
});
_deferred.resolve('facebook');
};
//do some stuff after google maps load:
_deferred.done('gmap', function(){
...
});
//do some stuff after google maps and facebook load:
_deferred.done(['gmap', 'facebook'], function(){
...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment