mo.notono.us

Tuesday, March 01, 2011

Practical example of jQuery 1.5’s deferred.when() and .then()

"“Fun with jQuery Templating and AJAX” by Dan Wellman is a generally interesting article, but I found the code in the “Getting the Data” block especially interesting – see how each get function RETURNS the $.ajax function call, which can then be called inside a when() function, vastly simplifying the workflow (there’s an error in the listed code – getTweets() is supposed to return the ajax function, not simply execute it).

http://net.tutsplus.com/tutorials/javascript-ajax/fun-with-jquery-templating-and-ajax/

Even more interesting is this pattern, suggested by commenter Eric Hynds (whose blog has now been added to my Google Reader list):

http://net.tutsplus.com/tutorials/javascript-ajax/fun-with-jquery-templating-and-ajax/comment-page-1/#comment-357637

$.when( $.get('./tmpl/person.tmpl'), $.getJSON('path/to/data') )
   .then(function( template, data ){
      $.tmpl( template, data ).appendTo( "#people" );
   });

The deferred.done() and then() methods will take as arguments the results from each function called in the when() function – in order – i.e. the output of the get will map to template, and the output from the getJson will be mapped to data.  This is pretty sweet!

Perhaps a simpler to observe example of the behavior is shown here: http://jsfiddle.net/austegard/ZaFVg/ - no prize for correct guesses as to the result of this…

/* Hello and World are both treated as resolved deferreds - they 
can be replaced with any function, like a $.get, etc */
$.when( "Hello", "World" ).then(
   function(x, y){ alert(x + " " + y); }
);

Labels: , , , ,

0 Comments:

Post a Comment

<< Home