jQuery中$ .when.apply(null,方法)的含义是什么?

时间:2012-04-27 05:18:09

标签: jquery deferred

我正在读取jQuery中的延迟对象。有谁能告诉我以下两种调用方式有什么区别?

  1. $.when.apply(null, a method).done(function(){success callback})
  2. $.when.(a method).done(function(){success callback})
  3. 上述第一种方式适合哪种情况?

    提前致谢。

2 个答案:

答案 0 :(得分:16)

$.when.apply(null, a method)只有在方法实际上是数组或方法调用返回数组时才有意义。那就像$.when(elements, of, the, array)See MDN有关apply方法的详细说明。

$.when.(a method)毫无意义,但我想你的意思是$.when(a method)。在这种情况下,方法应该再次是方法调用返回延迟对象或指向延迟对象的变量。

$.when()的语法是$.when(one, or, more, deferreds) - 因此,如果要传递数组中的多个延迟,则需要.apply(),因为您不想构建方法调用作为一个字符串并使用eval(在这种情况下确实是邪恶)。

答案 1 :(得分:1)

创建延迟是为了在一些远程调用的响应之后执行代码(即: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);
});

在加载exacly 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
});
相关问题