The MooTools Request class gives us the option to link together requests so that with a single instance of the class, if you’ve got a request that’s running you can ‘stack up’ any new send requests so that they occur one after the other.
This is convenient, but what if you have numerous instances of Request or its subclasses (like Request.HTML) and you want to only have one request running at a time? Or only two?
That’s basically all that Request.Queue does. It lets you register any number of instances of Request or its subclasses with an instance of Request.Queue and then write your code like normal. All requests to server will be queued up and fired off one or two or three at a time (you choose).
I put this class together partially a while back but never really polished it up for release. I spent some time over the holiday break to write up the docs and get it ready for release after I saw this thread in the MooTools Users Group.
Here’s a quick example of what it looks like:
var num1 = new Request({ url: '/wiki/simple.php', data: {num: 1, sleep: 1}, method: 'get',
onComplete: function(response){ console.log(response) } });
var num2 = new Request({ url: '/wiki/simple.php', data: {num: 2, sleep: 1}, method: 'get',
onComplete: function(response){ console.log(response) } });
var num3 = new Request({ url: '/wiki/simple.php', data: {num: 3, sleep: 1}, method: 'get',
onComplete: function(response){ console.log(response) } });
var myQueue = new Request.Queue();
//you can add them one at a time
myQueue.addRequest('num1', num1);
//or in a single call
myQueue.addRequests({ num2: num2, num3: num3 });
num1.send();
num2.send();
num3.send();
The above example will only allow the instances of Request to run one at a time. Each one will run and when it gets a response the next item will then be sent. It integrates right into the Request (or Request.HTML or Request.JSON) class when you register it so you don’t have to really change anything.
Note that you can specify how many requests can run at a time. There are also numerous methods and options that you can use to configure things and use the class in numerous ways. I suggest you peruse the docs for all those details.
As always, you can download this from my download builder.