-->

jQuery的:$。当行为有所取决于数量的参数(Jquery: $.when behaves dif

2019-09-21 10:11发布

$。当行为不同取决于一种或多种Deferred对象是否传递给它。 这种行为被记录在文档 - 但问题是,它迫使我写两个不同的代码路径。

function foo (dfds) {
    $.when.apply(this, dfds).done(function() {
        console.log(arguments);
    });
}

案例一:

foo([$.getJSON("http://freegeoip.net/json/8.8.8.8"),
     $.getJSON("http://freegeoip.net/json/8.8.8.9")]);
....
/* Output (what I'd come to expect) */
[Array[3], Array[3]]

案例二:

foo([$.getJSON("http://freegeoip.net/json/8.8.8.8")]);
....
/* Output (the original unwrapped deferred's arguments) */
[Object, "success", Object]

任何方式很好地处理这种不诉诸检查的长度dfd或类型arguments

Answer 1:

我不认为你能避免明确的测试延期的对象的数量。 假设你想返回延期对象:

function foo (dfds) {
    if(dfds.length > 1) {
        return $.when.apply(this, dfds);
    }
    else {
        return dfds[0].pipe(function() {
            return [Array.prototype.slice.call(arguments, 0)]
        });
    }
}

你可以创建一个jQuery插件来包装此功能,并使其可重复使用:

(function($) {
    $.when_ = function() {
        if(arguments.length > 1) {
            return $.when.apply(this, arguments);
        }
        else {
            return arguments[0].pipe(function() {
                return [Array.prototype.slice.call(arguments, 0)];
            });
        }
    };
}(jQuery));

您也可以覆盖$.when ,但我不知道自己是否是内部或没有使用。



Answer 2:

jQuery有带参数的逻辑搞乱的一个坏习惯。 在你的情况,如果你想为每个延迟对象的回调一个简单的循环将其规范化:

$.each(dfds, function() {
    $.when(this).done(function() {
        console.log(arguments);
    });
});

您还可以循环的参数,所以你不必送数组:

function foo() {
    $.each(arguments, function() {
        $.when(this).done(function() {
            console.log(arguments);
        });
    });
}

UPDATE

如果你总是想返回延期对象的数组,你可能需要检查参数的长度foo像费利克斯发布,或做这样的事情:

function foo() {
    $.when.apply(this, arguments).done(function() {
        var args = $.makeArray(arguments),
            result = args[0].constructor != Array ? [args] : args;
        console.log(result);
    });
}

http://jsfiddle.net/2ht8d/



Answer 3:

只需按下一个虚拟对象到您的DFDS数组的末尾。 这将确保它总是有长度大于或等于2,假设你有至少一个延缓。



文章来源: Jquery: $.when behaves differently depending on number of arguments