$.when 的行为会有所不同,具体取决于是否将一个或多个 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
的类型的情况下优雅地处理这个问题?
最佳答案
我认为您无法避免显式测试延迟对象的数量。假设您要返回延迟的对象:
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
但我不确定它是否在内部使用。
关于javascript - Jquery:$.when 根据参数的数量表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12050160/