【发布时间】:2012-04-27 05:18:08
【问题描述】:
我正在阅读 jQuery 中的延迟对象。谁能告诉我以下两种调用方式有什么区别?
$.when.apply(null, a method).done(function(){success callback})$.when.(a method).done(function(){success callback})
上面的第一种方式适合什么样的情况?
提前致谢。
【问题讨论】:
我正在阅读 jQuery 中的延迟对象。谁能告诉我以下两种调用方式有什么区别?
$.when.apply(null, a method).done(function(){success callback})$.when.(a method).done(function(){success callback})上面的第一种方式适合什么样的情况?
提前致谢。
【问题讨论】:
$.when.apply(null, a method) 仅在 a 方法 实际上是一个数组或 call 返回数组的方法时才有意义。然后就像$.when(elements, of, the, array)。 See MDN 获取apply 方法的详细说明。
$.when.(a method) 完全没有意义,但我猜你的意思是$.when(a method)。在这种情况下,方法应该再次是返回延迟对象或指向延迟对象的变量的方法调用。
$.when() 的语法是$.when(one, or, more, deferreds) - 所以如果你想传递数组中的多个延迟,你需要.apply(),因为你不想将方法调用构建为字符串并使用@ 987654333@(在这种情况下确实是邪恶的)。
【讨论】:
Deferred 是为了在响应某些远程调用(即:ajax)之后执行代码而创建的。
所以你可以:
load_conf = function (user_id) {
var def = $.Deferred()
$("http://get_conf_data_url?user_id="+user_id).done(function (data) {
var processed_conf = do_something_with(data);
def.resolve(processed_conf);
})
return def.promise();
}
所以你可以去:
load_conf(1).done(function (processed_data) {
do_something_with(processed_data);
});
在加载完 3 个配置后执行一些代码会怎样? 你可以这样做:
$.when(load_conf(1), load_conf(2), load_conf(3)).done(function (c1, c2 ,c3) {
console.log("configurations: ", c1, c2, c3);
})
但是在加载 N 是可变的 N 个配置之后执行一些代码呢? 对于这种情况,您可以使用 Function.prptotype.apply 方法。 您可以将一个对象作为第一个参数传递,该对象将在函数内被视为“this”。 第二个参数是参数列表,但在数组中。
所以你可以这样:
var defs = [];
for (var i=1; i<=N; i++) {
defs.push(load_conf(i));
}
// here's the magic
$.when($,defs).done(function () {
console.log("All conf loaded: ", arguments);
// arguments contains N processed answers
});
【讨论】: