Quantcast
Channel: Over It. » jQuery
Viewing all articles
Browse latest Browse all 2

jQuery Deferreds

$
0
0

I’m absolutely loving the new Deferred objects in jQuery 1.5 and am using them heavily in a new project at work.

I just spent a bit of time trying to figure out why they weren’t working the way I was expecting them to, actually having to step into the jQuery code to realize my mistake.

The $.when method can take in one or more Deferred objects, but it can’t take them in as an array. Once I realized this, I immediately realized this could be solved with JavaScript’s apply function like this:

$.when.apply($, myDeferreds).done(function () {
    // All deferreds were resolved...
});

The first argument to apply is the object that gets to be “this” inside the when method. The second argument is the array containing the deferreds.

If myDeferreds contains three deferred objects, the above is the equivalent of this:

$.when(deferred1, deferred2, deferred3).done(function () {
    // All deferreds were resolved...
});

I thought that it would be neat if $.when would check to see if it was passed an array, but the jQuery team disagrees. Here’s hoping I won’t make this mistake again…


Viewing all articles
Browse latest Browse all 2

Trending Articles