另一个函数运行时的触发器功能

时间:2018-01-17 18:44:55

标签: javascript jwplayer

我正在使用jwplayer。我想使用jwplayer()。on(' ready')在视频播放器准备就绪时触发。通常,首先加载jwplayer()脚本,然后在视频播放器准备就绪时告诉客户端页面执行某些操作,例如。播放广告。不幸的是我的脚本首先被加载,所以我无法引用jwplayer()。on(' ready')命令而且我无法在播放器加载时做一些事情,因为客户还不知道玩家是什么。

例如。我想在另一个函数(" b")加载时触发脚本。我无法访问函数b,所以我无法承诺像.then这样的东西。函数b是一个全局变量,所以我可以通过窗口访问它。这是有用的。

    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();

我使用Math.random来模拟我不知道何时加载此脚本。显然这不是最佳的,因为我每隔5毫秒检查一次窗口。我查看了.addEventListener(&#39; load&#39;,)但这似乎并不是我想要的。还有另一种方法吗?

在这个JSFiddle中,我无法设置全局变量,因此我在窗口位置使用了obj。

&#13;
&#13;
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();
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

实际上,如果你创建了全局变量,你可以检测它何时发生变化

~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