I'm reading the deferred object in jQuery. Could anyone please tell me what's the difference between following two invoking way?
$.when.apply(null, a method).done(function(){success callback})
$.when.(a method).done(function(){success callback})
And what kind of cases are fit for the first way above?
Thanks in advance.
$.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).
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With