Created
December 19, 2011 07:44
-
-
Save khrome/1495937 to your computer and use it in GitHub Desktop.
String.whenInDOM : call a function on a DOM element from the future
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
if(!String.whenInDOM){ | |
if(!String.defaultReplacementTimeout) | |
String.defaultReplacementTimeout = 16384; | |
String.implement({ | |
whenInDOM : function( | |
callback, | |
delayCallback, | |
timeoutCallback, | |
timeout, | |
counter | |
){ | |
if(!timeout) timeout = String.defaultReplacementTimeout; | |
if(!counter) counter = 0; | |
if(!timeoutCallback) timeoutCallback = function(event){ | |
throw( | |
'Element did not appear in DOM(\''+event.id+ | |
'\') after '+event.time+'ms' | |
); | |
}; | |
if(!document.id(this)){ | |
// we want to get the DOM node when it appears | |
// so we're looking for a gradient falloff of intervals | |
// as it approaches timeout | |
var delayTime = Math.pow(2, counter); | |
if(delayTime >= timeout){ | |
timeoutCallback({ | |
id : this, | |
count : counter, | |
time : delayTime | |
}); | |
} | |
counter++; | |
this.whenInDOM.delay(delayTime, this, | |
[callback, delayCallback, timeoutCallback, timeout, counter] | |
); | |
if(delayCallback) delayCallback({ | |
count : counter, | |
time : delayTime | |
}); | |
}else{ | |
callback(document.id(this)); | |
} | |
} | |
}); | |
} |
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
'my_awesome_id'.whenInDOM(function(){ | |
//do stuff here | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment