Published: 11 Dec 2009
By: Manning Publications

This article is taken from the book jQuery in Action, second edition. This segment shows how you can create your own queue to queue up any functions that you'd like to have executed in serial order. An understanding of jQuery animation is assumed.

 

About the book

This is a sample chapter of the book jQuery in Action, Second Edition. It has been published with the exclusive permission of Manning.


Written by: Bear Bibeault and Yehuda Katz
Pages: 475
Publisher: Manning
ISBN: 9781935182320

Get 30% discount

DotNetSlacker readers can get 30% off the full print book or ebook at www.manning.com using the promo code dns30 at checkout.

Queuing up animations for serial execution is an obvious use for function queues. But is there a real benefit? After all, the animation methods allow for completion callbacks, why not just fire off the next animation in the callback of the previous animation?

Consider the following code fragment:

We see that we have two animations changing the top property, and two animations changing the left property. In fact, the animations for each property are doing the exact opposite of each other. Figure 1 shows the initial state of the page where we will observe the behavior of multiple, simultaneous animations.

Figure 1: Using function queuing, the animations happen in a serial fashion.

Using function queuing, the animations happen in a serial fashion.

So what should we expect? Might they just cancel each other out and the moon (our test subject) remain completely still? But no. Upon clicking Start and observing the behavior of the animations, we see that each animation happens in a serial fashion, one after the other, such that the Moon makes a complete and orderly revolution around the Earth (albeit in a very unnatural square orbit that would have made Kepler's head explode).

What's going on? The animations aren't blocking, yet they execute serially just as if they were (at least with respect to each other). What's happening is that, internally, jQuery is queuing up the animations and executing them serially on our behalf. Compare that to the equivalent code, which would be necessary without function queuing, using the completion callbacks:

It's not that the callback variant of the code is that much more complicated, but it'd be hard to argue that the original code isn't a lot easier to read (and to write in the first place). And if the bodies of the callback functions were to get substantially more complicated ... well, it's easy to see how being able to queue up the animations makes the code a lot less complex.

So what if we wanted to do the same thing with our own functions? Well, jQuery isn't greedy about its queues; we can create our own to queue up any functions that we'd like to have executed in serial order. Queues can be created on any element, and distinct queues can be created by using unique names for them (except for "fx" which is reserved for the effects queue). The method to add a function instance to a queue is, unsurprisingly, queue(), and it has three variants, as described in the following syntax:

Method syntax: queue

queue(name)

queue(name,function)

queue(name,queue)

The first form returns any queue of the passed name already established on the first element in the matched set as an array of functions. The second form adds the passed function to the end of the named queue for all elements in the matched set. If such a named queue does not exist on an element, it is created. The last form replaces any existing queue on the matched elements with the passed queue.

Parameters

name - (String) The name of the queue to be fetched, added to, or replaced. If omitted, the default effects queue of "fx" is assumed.

function - (Function) The function to be added to the end of the queue. When invoked, the function context (this) will be set to the DOM element upon which the queue has been established.

queue - (Array) An array of functions that replaces the existing functions in the named queue.

Returns

An array of functions for the first form, the wrapped set for the remaining forms.

The queue() method is most often used to add functions to the end of the named queue, but can also be used to fetch any existing functions in a queue, or to replace the list of functions in a queue. Note that the array form, in which an array of functions is passed to queue(), cannot be used to add multiple functions to the end of a queue as any existing queued functions are removed.

OK, so now we can queue functions up for execution. That's not all that useful unless we can somehow cause the execution of the functions to actually occur. Enter the dequeue() method:

Method syntax: dequeue

dequeue(name)

Removes the foremost function in the named queue for each element in the matched set and executes it for each element.

Parameters

name - (String) The name of the queue from which the foremost function is to be removed and executed. If omitted, the default effects queue of "fx" is assumed.

Returns

The wrapped set

When dequeue() is invoked, the foremost function in the named queue for each element in the wrapped set is executed with the function context for the invocation (this) being set to the element. Let's consider the code of listing 1:

Listing 1: Queuing and dequeuing functions on multiple elements

In this example, we have two images upon which we establish queues named "chain". In each queue, we place four functions that identify themselves in order and emit the alt attribute of whatever DOM element is serving as the function context. This way, we can tell which function is being executed, and from which element's queue.

Upon clicking the Dequeue button, the button's click handler causes a single execution of the dequeue() method. Go ahead and click the button once, and observe the messages in the console as shown in figure 2:

Figure 2: Clicking the Dequeue button causes a single queued instance of the function to fire, once for each image that it was established upon.

Clicking the 

Dequeue button causes a single queued instance of the function to fire, once for each image that it was established upon.

We can see that the first function we added to the "chain" queue for the images has been fired twice: once for the Earth image, and once for the Moon image. Clicking the button subsequent times removes the next function from the queues and executes them until the queues have been emptied; after which, calling dequeue() has no effect.

In this example, the dequeuing of the functions was under manual control - we needed to click the button four times (resulting in four calls to dequeue()) to get all four functions executed. Frequently we may want to trigger the execution of the entire set of queued functions. For such times, a commonly used idiom is to call the dequeue() method within the queued function in order to trigger the execution of (in other words, "chain to") the next queued function.

Consider the following changes to our above example:

If you were to open this code in your browser and click the Dequeue button, the single click now triggers the execution of the entire chain of queued functions.

Get 30% discount

DotNetSlacker readers can get 30% off the full print book or ebook at www.manning.com using the promo code dns30 at checkout.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Manning Publications

Manning Publication publishes computer books for professionals--programmers, system administrators, designers, architects, managers and others. Our focus is on computing titles at professional levels. We care about the quality of our books. We work with our authors to coax out of them the best writi...

This author has published 33 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
Book Review: Pro JavaScript Design Patterns
Brain Mains reviews Pro JavaScript Design Patterns.
Test120Jan
This is my custom article

You might also be interested in the following related blog posts


Only a few hours left (part 5) read more
Top
 
 
 

Please login to rate or to leave a comment.