What's the meaning of $.when.apply(null, a method) in jQuery?

不打扰是莪最后的温柔 提交于 2019-12-12 10:53:48

问题


I'm reading the deferred object in jQuery. Could anyone please tell me what's the difference between following two invoking way?

  1. $.when.apply(null, a method).done(function(){success callback})
  2. $.when.(a method).done(function(){success callback})

And what kind of cases are fit for the first way above?

Thanks in advance.


回答1:


$.when.apply(null, a method) only makes sense if a method is actually an array or a method call returning an array. Then it's like a $.when(elements, of, the, array). See MDN for a detailed description of the apply method.

$.when.(a method) makes no sense at all, but I guess you meant $.when(a method). In this case a method should again be a method call returning a deferred object or a variable that points to a deferred object.

The syntax of $.when() is $.when(one, or, more, deferreds) - so if you want to pass multiple deferreds which are in an array, you need .apply() since you don't want to build the method call as a string and use eval (which is indeed evil in this case).




回答2:


Deferred was created to execute code after the response of some remote invocation (i.e.: ajax).

so you could have:

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();
}

so you could go:

load_conf(1).done(function (processed_data) {
    do_something_with(processed_data);
});

What about to execute some code after loading exacly 3 configurations? You could do something like:

$.when(load_conf(1), load_conf(2), load_conf(3)).done(function (c1, c2 ,c3) {
     console.log("configurations: ", c1, c2, c3);
})

But what about executing some code after loading N configurations where N is variable? For this cases you can use the Function.prptotype.apply method. You can pass as first argument an object that will be treated as "this" inside the function. The second argument is the list of parameters but inside an array.

so you can go like 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
});


来源:https://stackoverflow.com/questions/10345124/whats-the-meaning-of-when-applynull-a-method-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!