ProgFu

programming tips & tricks

Feb 20

Deferred Objects in jQuery 1.5 - AJAX

The latest version of our beloved jQuery introduced a couple of new features, one of which is called Deffered Objects. Now what is that exactly?

We often need to introduce some sort of a callback mechanism in JavaScript, where a function is invoked once a task is done. The most popular usecase would be AJAX.

If you wanted to create a AJAX request and then work with the response (prior to jQuery 1.5), you would use the following code:

$.get("/example.html", function(data) {
    // ... here we work with the response
});

While this feels perfectly natural, there are some scenarios where it just doesn’t work so well. Like what if you wanted to add the callback later on?

That’s exactly where the new 1.5 feature comes in. We could write the same code like this:

request = $.get("/example.html");    
request.success(function(data) {
    // ... the same handler code as above
});

Doesn’t that look nice? Now the first question that probably popped in everyone’s head is “What happens if the GET request finishes before the callback is assigned?”. And the answer is, fortunately, it gets invoked immediately after it is assigned.

That’s the beautiful thing about Deferred Objects. You can assign the callback later on, and it still gets called.

You can also assign a error handler in the same fashion

request.error(handleError);

But this is only the begining of what Deferred Objects can do. In the next article, we’ll take a look at some even more awesome features.


Page 1 of 1