Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 708
user1338323 Avatar asked Apr 27 '12 05:04

user1338323


2 Answers

$.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).

like image 91
ThiefMaster Avatar answered Sep 28 '22 08:09

ThiefMaster


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
});
like image 27
Viter Rod Avatar answered Sep 28 '22 09:09

Viter Rod