Reputation: 1
I'm working with jwplayer. I would like to use jwplayer().on('ready') which fires when the video player is ready. Normally the jwplayer() scripts load first, then I'd tell the client page to do something when the video player is ready eg. play ad. Unfortunately my scripts are being loaded first, so I can't reference the jwplayer().on('ready') command and I can't say do something when the player is loaded, because the client doesn't know what a the player is yet.
For example. I'd like to trigger a script once another function ("b") loads. I do not have access to the function b so I can't put in promises for something like .then . function b is a global variable so I can access it by window. Here is something that works.
var num = Math.random() * 2000;
setTimeout(function(){
function b(){
//b stuff
}}, num);
-
var counterA = 0;
function bFind(){
if(counterA <= 3000){
//if (Object.keys(window).indexOf("b") != -1){
if (window.hasOwnProperty("b") == true){
//a stuff
alert(counterA);
}
else{
setTimeout(function(){
counterA += 5;
bFind();
}, 5)
} } }
bFind();
I use Math.random to simulate that I don't know when this script is going to be loaded. Obviously this isn't optimal since I am checking the window every 5 ms. I have looked into .addEventListener('load',) but that doesn't seem to be what I'm looking for. Is there another way to do this?
In this JSFiddle I can't set global variables so I've used obj in the place of window.
var num = Math.random() * 2000;
var obj = {a: ""};
setTimeout(function(){
obj = {
a: ["hello","world"],
b: ["foo","bar"]
};
}, num);
/*_____________________________________*/
var counterA = 0;
function bFind(){
if(counterA <= 3000){
//if (Object.keys(obj).indexOf("b") != -1){
if (obj.hasOwnProperty("b") == true){
document.write(counterA);
}
else{
setTimeout(function(){
counterA += 100;
document.write("_");
bFind();
}, 100)
} } }
bFind();
Upvotes: 0
Views: 84
Reputation: 1379
In fact if the global variable is created by you you can detect when it change
~function(){
var hiddenValue;
Object.defineProperty(window, "myGlobalVar", {
set: function (x) {
hiddenValue = x
console.log("value has changed")
},
get: function(x){
return hiddenValue
},
enumerable: true,
configurable: true
});
}()
myGlobalVar = 9
Upvotes: 0