Skip to content

Instantly share code, notes, and snippets.

@OwenMelbz
Created April 14, 2016 18:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OwenMelbz/fd607a800130e8a4ad8dc07a39ff3f38 to your computer and use it in GitHub Desktop.
Save OwenMelbz/fd607a800130e8a4ad8dc07a39ff3f38 to your computer and use it in GitHub Desktop.
Helper function that fires when an object becomes avaiable
//Inspired by http://fokkezb.nl/2016/04/14/how-to-wait-for-a-javascript-variable-to-be-defined/
//var console = document.getElementById('console');
//console.innerText = 'not loaded';
var whenDefined = function($context, $variable, $callback){
if( $context[$variable] ){
$callback();
} else {
Object.defineProperty($context, $variable, {
configurable: true,
enumerable: true,
writeable: true,
get: function() {
return this['_' + $variable];
},
set: function(val) {
this['_' + $variable] = val;
$callback();
}
});
}
}
//whenDefined(window, 'intercomSettings', function() {
// console.innerText = 'loaded';
//});
//setTimeout(function(){
// window.intercomSettings = {blar: 'blar'};
//}, 3000)
@Aure77
Copy link

Aure77 commented May 12, 2021

whenDefined(window, 'intercomSettings', function() {
  console.log("defined1");
});
whenDefined(window, 'intercomSettings', function() {
  console.log("defined2");
});
setTimeout(function(){
  window.intercomSettings = {blar: 'blar'};
}, 3000);

defined1 is never printed because 2nd whenDefined override property (due to same context/variable) previously defined.

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