What does the value of $ .when.apply (null, method) mean in jQuery?

I am reading a pending object in jQuery. Can someone please tell me what is the difference between the next two calls?

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

And what cases are suitable for the first method above?

Thanks in advance.

+6
source share
2 answers

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

$.when.(a method) doesn't make any sense, but I think you mean $.when(a method) . In this case, the method should again be a method call that returns a deferred object or variable that points to the deferred object.

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

+16
source

Deferred was created to execute the code after answering some remote call (i.e.: ajax).

so you can:

 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 can go:

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

How to execute some code after loading exacly 3 configurations? You can 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 the execution of some code after loading the N-configurations, where N is a variable? In this case, you can use the Function.prptotype.apply method. You can pass an object to be considered as "this" inside the function as the first argument. The second argument is a list of parameters, but inside the array.

so you can do the following:

 var defs = []; for (var i=1; i<=N; i++) { defs.push(load_conf(i)); } // here the magic $.when($,defs).done(function () { console.log("All conf loaded: ", arguments); // arguments contains N processed answers }); 
+1
source

Source: https://habr.com/ru/post/914291/


All Articles