Created
August 3, 2012 20:31
-
-
Save nickjacob/3251282 to your computer and use it in GitHub Desktop.
A little javascript that lets you setup calls to a script that you aren't sure has loaded yet. You could load this script in too
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sometimes you're working with a script hosted on a server that you can't be sure is going to ever return/you don't know when | |
* this script lets you make calls to the object it is eventually going to add to the window object before it's there. | |
* this is (probably) very similar to the code behind google analytic's _gaq.push() | |
*/ | |
(function(watch_list,future_obj,interval){ | |
var noop = function(){}, _func_ = 'function'; | |
var __asynch = function(list,obj,intr){ | |
this.intr=(typeof intr==='number') ? intr : 500;this.loop=null;this.obj = obj; this.calls = [];var self = this; list = list || []; | |
for(var i=0,l=list.length;i <l;i++) this.calls[i] = list[i]; | |
list.push = function(){ return self.add_call.apply(self,arguments); }; | |
}; | |
__asynch.prototype.add_call = function(){ | |
var args = Array.prototype.slice.apply(arguments),self=this; | |
for(var i=0,l=args.length;i<l;i++) self.calls.push(args[i]); | |
self.init.apply(self); | |
}; | |
__asynch.prototype.launch = function() { | |
var self=this; | |
for(var j=0,len=self.calls.length; j < len; j++){ inner_call(self.calls[j]); } | |
function inner_call(call){ | |
var tmp = self.obj, cb = (typeof call[1]===_func_) ? call[1] : noop, args = call[2] || []; | |
var mthd = (typeof call[0]===_func_) ? function(){ call[0].call(self.obj,self.obj);} : (function(m){ | |
for(var i=0,l=m.length; i <l; i++){ if(tmp[m[i]]===void(tmp = tmp[m[i]])) return noop;} | |
return function(){ tmp.apply(self.obj,args);}; | |
})(call[0].split('.')); | |
return cb(mthd()); | |
} | |
self.calls = []; | |
}; | |
__asynch.prototype.init = function() { | |
var self = this; | |
if(self.obj===void(0)){ | |
if(self.loop!==null) return; // still waiting | |
self.loop = setInterval(function(){ | |
if(self.obj!==void(0)){ | |
self.launch.apply(self); | |
clearInterval(self.loop); | |
} | |
},self.intr); | |
} else self.launch.apply(self); | |
}; | |
if(typeof watch_list !== 'object' || !(watch_list instanceof Array)) window[watch_list] = []; | |
var asynch = new __asynch(watch_list,future_obj,interval); | |
})(window.call_list,window.Future_Object,500); | |
// usage | |
window.call_list = []; | |
window.call_list.push(['method_name',callback,[arguments]]); // to call methods on the object | |
window.call_list.push([function(obj){},callback,[arguments]]); // to call a function & have object passed in |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment