Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将新jquery添加到现有的$。何时?_Javascript_Jquery_Jquery Deferred - Fatal编程技术网

Javascript 如何将新jquery添加到现有的$。何时?

Javascript 如何将新jquery添加到现有的$。何时?,javascript,jquery,jquery-deferred,Javascript,Jquery,Jquery Deferred,我正在重构一个资源加载函数,它使用传统的回调模式来代替jQuery延迟 此函数获取URL和URL数组,为每个资源创建一个新的延迟对象,创建一个$延迟对象来监视它们,并返回$延迟对象的承诺 以下是该方法的简化版本: theLib = { getResources : function(paths) { var deferreds = []; theLib.isLoading = true; $.each(paths, function(i,

我正在重构一个资源加载函数,它使用传统的回调模式来代替jQuery延迟

此函数获取URL和URL数组,为每个资源创建一个新的延迟对象,创建一个
$延迟对象来监视它们,并返回
$延迟对象的承诺

以下是该方法的简化版本:

theLib = {
    getResources : function(paths) {
        var deferreds = [];
        theLib.isLoading = true;
        $.each(paths, function(i, path) {
            // do something with the path, either using getScript
            // or making a new $.Deferred as needed
            deferreds.push(/* the deferred object from above comment */);
        });
        theLib.currentDeferred = $.when.apply(null,deferreds).always(function() {
            theLib.isLoading = false;
        });

        return theLib.currentDeferred.promise();
};
这很有效

我的问题是:在旧脚本中,不仅要根据用户操作或事件调用lib.getResources()
,而且还要定义一个资源主列表,当用户不采取任何操作(即阅读文章)时,应用程序将“流式传输”这些资源

其中一些流式资源与用户执行操作时可以手动调用的资源相同。该脚本非常聪明,通过跟踪加载的内容,不会两次加载资源

它还跟踪
库的isLoading
。该函数的开头是这样的:

getResources : function(paths, callback) {
    if (theLib.isLoading) {
        settimeout(function() {
            theLib.getResources(paths, callback);
        }, 100);
    }
    theLib.isLoading = true;
我不能再这样做了,因为我需要返回一个承诺对象


我知道我可以检查lib.currentDeferred.isResolved()
。在这一点上,如果问题没有解决:我如何向
$添加更多延迟对象。当
正在监视的队列时?

我想我需要问这个问题来为自己找到解决方案。基本上,我在
getResources
的开头添加了以下代码:

if(!theLib.currentDeferred.isResolved()){
返回$.when(lib.currentDeferred).always(函数(){
theLib.getResources(路径);
}).promise();
}

上述措施失败了。正确的解决方案是通过管道输送结果:

if ( ! theLib.currentDeferred.isResolved()) {
    return theLib.currentDeferred.pipe(function() {
        return theLib.getResources(paths);
    });
}