jQuery:$ .when的行为根据参数数量而有所不同 [英] Jquery: $.when behaves differently depending on number of arguments
问题描述
$.何时行为取决于是否将一个或多个Deferred对象传递给它.此行为已在文档中进行了记录-但问题是它迫使我编写了两个不同的代码路径.
$.when behaves differently depending on whether one or more Deferred object are passed to it. This behaviour is documented in the docs - but the problem is that it is forcing me to write two different code paths.
function foo (dfds) {
$.when.apply(this, dfds).done(function() {
console.log(arguments);
});
}
案例1:
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
的类型?
Any way to elegantly handle this without resorting to checking the length of dfd
or the type of arguments
?
推荐答案
我认为您不能避免显式测试延迟对象的数量.假设您要返回延迟的对象:
I don't think you can avoid explicit testing the number of deferred objects. Assuming you want to return the deferred object:
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插件来包装此功能并使其可重用:
You could create a jQuery plugin to wrap this functionality and make it reusable:
(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
,但是我不确定是否在内部使用它.
You could also override $.when
but I don't know for sure whether it is used internally or not.
这篇关于jQuery:$ .when的行为根据参数数量而有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!