javascript - 等待变量存在然后在 javascript 中执行某些操作

标签 javascript multithreading function callback

我有一个脚本,该脚本将在加载它必须读取的变量之前执行。

这是我的脚本,将首先执行

funcThatWaits(varToWait).ready(function(){
        //callback time!!
    alert("varToBeWait is Ready!!");
});

这是接下来要加载的脚本

var varToWait=null;

我想要的只是创建一个函数,该函数将等待变量存在,并在检测到变量已存在时自动执行回调。(这意味着当变量不存在时,它将等待)

这可能吗?我的第一个脚本完全复制在 jquery 的 $(document).ready() 函数上,等待 DOM 完全加载...这对于 JS 变量来说可能吗?

最佳答案

如果您的变量来自另一个函数(也可能来自另一个作用域),那么您可以传递回调并在第二个函数执行回调时为其提供变量。您不需要等待它何时存在,但您将等到第二个脚本为您提供它

//in the second script:

var varIWant = 'foo'

function fromSecondScript(callback){
    callback(varIWant);
}

//in the first script:

function fromFirstScript(){
    fromSecondScript(function(theVar){
        //"theVar" in this function scope is "varIWant" from the other scope
    })
}

另一种方法是预先定义一个加载器脚本来聚合回调并在设置变量后调用它们:

var aggregator = (function(){
    var stored = {};

    return {
        //adds a callback to storage
        addCallback : function(varName,callback){
            if(!stored.hasOwnProperty(varName)){
                stored[varName] = [];
            }
            stored[varName].push(callback);
        },
        //executes stored callbacks providing them data
        execute : function(varName,data){
            if(stored.hasOwnProperty(varName)){
                for(var i=0;i<stored[varName].length;i++){
                    stored[varName][i](data)
                }
            }
        }
}());

//in the first script add callbacks. you can add any number of callbacks
aggregator.addCallback('VarExists',function(theVar){
    //do what you want when it exists
});

aggregator.addCallback('VarExists',function(theVar){
    //another callback to execute when var exists
});

//in the second script, execute the callbacks of the given name
aggregator.execute('VarExists',theVarYouWantToShare);

关于javascript - 等待变量存在然后在 javascript 中执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10188196/

相关文章:

c - 指针和多线程中的错误预期为 ‘void * (*)(void *)’ 但参数的类型为 ‘pthread_t’

java - 编写这个函数的更好方法是什么?

在 C 中检查自己的 pow 函数的限制?

javascript - 对 PouchDB Promise 的结果使用 ng-repeat

javascript - 将属性添加到 jQuery 中的 &lt;input&gt; 每个循环仅在第一次通过时?

c++ - : How to make threads write to private arrays and merge all the arrays once all the threads finished processing 并行 omp

c++ - 函数、数组和动态数组

javascript - Backbone 集合获取所有模型,但仅设置一个

javascript - CSS - 纯 CSS + AngularJS 中的旋钮光标

c# - java中的线程数组