31
Jan

Chaining with MooTools 1.2 – Tutorial

This guide will show how powerful the MooTools Chain class is. In MooTools chaining facilitates the execution of a stack of functions sequentially and is extremely powerful. I have only tested this in MooTools v1.2 beta 2.

I will be posting more of these short guides on using MooTools in the upcoming weeks. Each will focus on a small problem and solve it with MooTools with the aim of being a useful way to learn the framework.

Chaining you say!

Chaining is very powerful and whilst it is similar to Effect.Queue in Script.aculo.us, it can do much more! The aim of this brief tutorial is to show you how to use MooTools Chaining in the context of queueing effects coupled with other arbitrary actions. However, you will see that you can easily apply Chaining to do much more than that.

From the MooTools 1.2 Docs:

A Utility Class which executes functions one after another, with each function firing after completion of the previous. Its methods can be implemented with Class:implement into any Class, and it is currently implemented in Fx and Request. In Fx, for example, it is used to create custom, complex animations.

Chain can be used as a stand-alone class but becomes much more powerful if you implement it into classes of your own.

In this tutorial I will be creating a class which implements Chain. The Chain class belongs to the Class.Extras component so you will need to make sure that you select Class.Extras and all its dependencies when downloading MooTools.

Implementing Chain

First of all we need to implement the methods and properties of the Chain class into our own class:

[codesyntax lang="javascript"]
var ChainExample = new Class({

  Implements: [Chain]

});
[/codesyntax]

Our class now has the following methods available to it:

  • Chain::chain – Pass any number of functions to add them to the bottom of the call stack.
  • Chain::callChain – Pops a function off the top of the call stack and executes it.
  • Chain::clearChain – Removes all functions from the call stack without executing any.

Using Chain to Execute Actions in Order

Now we have implemented Chain into our ChainExample class we are ready to make use of the functionality it provides.

The ChainExample class will add events to three button elements. When a button element is clicked a corresponding panel will appear. Before this happens all other panels will be faded out. Chaining is used to make sure that these events happen in the order we want.

The full code for ChainExample is:

[codesyntax lang="javascript"]
/**

 * Add events to buttons. Clicking a button will hide all panels before showing the panel corresponding to that button

 */

var ChainExample = new Class({

    Implements: [Chain],

    /**

     * Define the element ID of the button and the element ID of the corresponding panel

     */

    actions: new Hash({

        'button-one': 'panel-one',

        'button-two': 'panel-two',

        'button-three': 'panel-three'

    }),

    /**

     * An Array to store an effect instance for each panel

     */

    effects: [],

    initialize: function()

    {

        /**

         * Add an onclick event to each button. Clicking a button calls the showPanel method

         */

        this.actions.getKeys().each(function(buttonId) {

            $(buttonId).addEvent('click', this.showPanel.bindWithEvent(this));

        },this);

        /**

         * Create an Fx object for each panel

         */

         this.actions.getValues().each(function(panelId) {

            this.effects[panelId] = new Fx.Tween($(panelId), 'opacity', { duration: 'short', onComplete: function() { this.callChain();}.bind(this)});

         }, this);         /**

          * Initialize by hiding all panels, note the call to callChain to cause stuff to happen

          */

        this.hideAll();

        this.callChain();

    },

    /**

     * Add the a actions required to hide all panels to the Chain call stack

     */

    hideAll: function()

    {

        /**

         * loop each panel and Chain: 1. fade the panel, 2. set the display property to "none" after the effect has finished.

         *

         * Note that this function does not actually cause anything to happen, it simply adds actions to the Chain

         */

        this.actions.getValues().each(function(panelId) {

            this.chain(

                function() { this.effects[panelId].start(0); },

                function() { $(panelId).setStyles({'display': 'none'}); this.callChain(); }

            );

        },this);

    },

    /**

     * Handle a button click by fading and hiding all open panels and then appearing the corresponding panel

     */

    showPanel: function(event)

    {

        this.hideAll();

        var panel = this.actions.get(event.target.get('id'));

        this.chain(

            function() { $(panel).setStyles({'display': 'block', 'opacity': '0'}); this.callChain(); },

            function() { this.effects[panel].start(1); }

        );

        this.callChain(); //this call starts the chain. Since each function in the call also makes a call to callChain the entire stack will be executed

    }

});

window.addEvent('domready',

    function()

    {

        var myChain = new ChainExample();

    }

);
[/codesyntax]

I will only go through the code relevant to chaining in detail. Lets have a look at each important part:

ChainExample::initialize

In the constructor we bind behaviours to the buttons and create Fx objects for the panels. Notice the custom onComplete callback provided for each Fx instance. This tells the internal chain stack to pop the next function and run it right after the effect has finished. We are now able to execute any function as soon as the effect completes.

ChainExample::hideAll

Look at this method carefully. A call to ChainExample::hideAll() does not actually hide the panels. The method adds to the chain stack a set of functions that will fade and hide each panel in order. To get the panels to actually hide we must execute the chain stack using this.callChain().

Notice how the second function passed to this.chain invokes this.callChain(). The function is telling the chain stack to continue onto the next function by itself.

Another important thing to note is that there is no need to bind the function passed to this.chain as this is dealt with internally.

ChainExample::showPanel

This is the event handling function that will show a panel.

First off a call to ChainExample::hideAll() is made. Remember that this method doesn’t cause anything to happen immediately. At this point we have added all the steps needed to hide all the panels to the chain stack. We then proceed to add steps which will show the correct panel.

Once the entire chain stack is set up this.callChain() is executed and the entire stack will be called because each step makes its own call to this.callChain() once it has finished.

That’s the basics of Chain. We have created a class which allows us to combine any number of effects and arbitrary functions and ensure that the are executed in the order we want. Hence the basic idea of Chain is to create a stack of functions and execute them in the order you please whenever you please.

Downloadable Demo

I have put together a quick demo so that you can see the code in action. Download the demo here.

Further Considerations

In my example, every function in the chain stack makes a call to this.callChain() once is has completed. This means that as soon as the first function is executed (by manually invoking this.callChain()) the entire stack will run from start to finish automatically. Chain can be used in a different fashion where Chain::callChain() is always invoked externally. As a crude modification to my example, every click on a button could invoke this.callChain(). Thus each button click takes one further step to completion of the actions.

If you need to add timings and delays consider using Function:delay to delay the invocation of Chain::callChain().

It is also possible to use multiple chains in the same class for even more complex behaviour. This would involve using separate instances of the Chain class directly.