How are $ .when, apply () and $ .done () related in this function?

Some time ago, a SO user wrote this function for me to return a variable number of jQuery queries $.get(). The first part is pretty simple, but someone will explain how to interact $.when(), apply()and $.done(). I don’t understand at all, but it’s very specific how they access the deferred object returned $.get().

function getHTML(qty_of_gets) {

   var dfdArr = [],
       i = 1;

   while (i <= qty_of_gets) {
       dfdArr.push($.get("get_test_" + i + ".php"));
       i++;
   }

   $.when.apply(null, dfdArr).done(function () {

       for (var i = 0; i < arguments.length; i++) {

           $("#content").append(arguments[i][0]);

       }

   });
}
+3
source share
3 answers

$.whenreturns a new promise, so it $.when().done()simply calls .doneon the promise returned $.when.

.applyallows you to call a function with arguments in an array, and not pass them separately. So

$.when.apply(null, dfdArr)

(almost *) equivalent

$.when(dfdArr[0], dfdArr[1], dfdArr[2], ...);

dfdArr .


*, this .

+11

$.get() . , "", :

dfdArr.push($.get("get_test_" + i + ".php"));

$.when() . , , , . - :

$.when(dfd1, dfd2).done(function (dfd1Result, dfd2Result) {
    // The parameters from dfd1.done and dfd2.done are here in dfd1REsult, dfd2Result
}

, . .apply() . .

, , . , arguments, .

+3

The code creates an array of pending messages representing AJAX ( dfdArr) requests and populates it while.

Then it is applyused on $.when, so that all these deferred are passed to it as arguments. This leads to the return of the promise, which ends when all the initial deferrals were successful, i.e. When all AJAX requests have returned.

In other words, a call applyis the software equivalent of a record

$.when(dfdArr[0], ..., dfdArr[qty_of_gets - 1]).done(...);
+1
source

All Articles