Tag Archives: jquery

Simultaneous AJAX requests with jQuery’s $.When

Let’s say you need to request different services, but only continue your flow (show a dialog, enable some UI element, navigate, etc) when all those calls are complete. That is something you may achieve in several ways, like a timer, a flag check, etc. but jQuery provides a really powerful method called $.when that is based on Deferred object that receives N amount of $.ajax requests and chained either with $.done, $.fail, or $.then you can act based on all responses of your services. It really worth the reading on jQuery documentation ;) and here is a quick example.

The below code performs 3 “simultaneous” requests to Twitter Search API and by chaining with $.then we’ll receive on the callback the result of the 3 requests. Note that this is by far the best implementation and it is only this way to easy the example and focus on $.when functionality.

 

function getAjaxRequest(query) {
	return $.ajax({
		url: 'http://search.twitter.com/search.json',
		dataType: 'jsonp',
		data: {
			q: query,
			result_type: 'recent'
		}
	});
}

$(function() {
	$.when(getAjaxRequest('jquery'), getAjaxRequest('javascript'), getAjaxRequest('backbonejs')).then(function(jquery, javascript, backbonejs) {

		$.each(jquery[0].results, function(key, item){
			$('#jquery').append('<li><strong>' + item.from_user + '</strong>: ' + item.text + '</li>');
		});

		$.each(javascript[0].results, function(key, item){
			$('#javascript').append('<li><strong>' + item.from_user + '</strong>: ' + item.text + '</li>');
		});

		$.each(backbonejs[0].results, function(key, item){
			$('#backbonejs').append('<li><strong>' + item.from_user + '</strong>: ' + item.text + '</li>');
		});
	});
});

 

You can also watch it here or look at the code here.

Asynchronous loop with jQuery Deferred

On my previous experience with Flex I faced several times the necessity of delegate heavy loops to asynchronous processes; that was because either, the loop was too big or because each item required some heavy data or UI processing.

I was reading today about jQuery’s Deferred object (used mainly on $.when) and I decided to read more about it, understand it and use it when I required it. Deferred is a really simple but powerful object for some situations and one of those turns to be the asynchronous loops.

After some reading, brain overheat, and testing I came with this async loop that receive an options object with 4 properties:

  • total: The number of iterations. By default 0.
  • context: your this context to be sent to the callbacks. By default the loop this object.
  • limit: How many iterations before doing a pause. By default 100.
  • pause: A pause in milliseconds between each chunk. By default 10.

The more useful options are total and context. With those you can create an asynchronous loop that, upon each callback for each iteration will contain the proper this object.

var asyncFor = function(params) {
    var defaults = {
      total: 0,
      limit: 100,
      pause: 10,
      context: this
    },
      options = $.extend(defaults, params),
      def = $.Deferred(),
      step = 0,
      done = 0;

    this.loop = function() {
      if (done < options.total) {
        step = 0;
        for (; step < options.limit; step += 1, done += 1) {
          def.notifyWith(options.context, [done]);
        }
        setTimeout.apply(this, [this.loop, options.pause]);
      } else {
        def.resolveWith(options.context);
      }
    };

    setTimeout.apply(this, [this.loop, options.pause]);
    return def;
  };

 

And a simple example on how to use it:

asyncFor({
  total: 10,
  context: this
}).progress(function(step) {
  console.log(step);
}).done(function() {
  console.log('complete!')
});

 

As a plus, a more complete example demonstrates the big difference while looping 10,000 times synchronously and asynchronously.

Backbone Workshop – Episode 1: What the heck is Backbone?

Backbone.js LogoFirst of all, Backbone is cool; if you use it, by extension you are cool 8) !

Backbone is a framework that provides you with awesome tools to develop your web applications. From their site:

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

I like to think about Backbone as an “MVC” (without actually the “C”). In my words, Backbone is a collection of objects with functions that provides structure to your code and make your life way easier by providing you with awesome tools to work with your data, html, events, services, etc.

Backbone is not a replacement of jQuery, in fact it requires jQuery as a dependency.

Continue reading