PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 3, Prototype Data Types

The each() Method

Let's firstly look at the each() method, which is one of the most important functions made available to Enumerablecode> objects. In order to use each(), you pass an iterator function as the first argument. When the each() call is executed, the iterator function is called once for each element in the enumerable object. The current element is passed as the first argument to the iterator, while the second argument containers the iteration number (beginning from 0).

In order to demonstrate, let's revisit the $$() function. This function returns an array of elements that match the CSS selector(s) passed in as arguments. Using each(), we can easily perform operations on every matched element.

Listing 4 shows two examples of selecting all of the items in an unordered list and changing them slightly. We've already seen how $$() and the update() method works in previous articles, but we're now also using each(). In the first part of the example we define the iterator callback inline when performing the each, while in the second part of the example it is defined as a separate function.

Listing 4 Basic usage of each() on an array (listing-4.html)
<html>
    <head>
        <title>Basic usage of each() on an array</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo">
            <ul>
                <li>Element 1</li>
                <li>Element 2</li>
                <li>Element 3</li>
                <li>Element 4</li>
            </ul>
        </div>
 
        <script type="text/javascript">
            $$('#foo li').each(function(item) {
                item.update(item.innerHTML + ' -- modified!');
            });
 
            function doSomething(item)
            {
                item.setStyle({ backgroundColor : '#f60' });
            }
 
            $$('#foo li').each(doSomething);
        </script>
    </body>
</html>

When using each() to loop over data, it is important to know how to control the loop. In PHP (and other languages), you can use the break or continue expressions to do so. Using break in PHP means the loop execution is halted there and then, while continue halts the current iteration but continues on with the loop.

Achieving continue functionality within each() is simple. Because each iteration is a function call, you can simply use return to emulate continue. The current function call is terminated and the function will be called again for the next iteration.

In order to break the loop, Prototype provides a special variable called $break. If you throw this variable as an exception, Prototype will know to end the loop. Listing 5 shows an example of continuing and breaking a loop. This example will read the text inside each list item and write it to the #output div.

As mentioned above, the iteration number is passed as the second argument to the iterator callback. In this example we skip outputting a message for the third iteration, and finish the loop after the fourth element.

Note: The iteration number is zero-indexed, so this value will be 2 for the third iteration and 3 for the fourth iteration.
Listing 5 Breaking and continuing each() loops (listing-5.html)
<html>
    <head>
        <title>Breaking and continuing each() loops</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo">
            <ul>
                <li>Element 1</li>
                <li>Element 2</li>
                <li>Element 3</li>
                <li>Element 4</li>
                <li>Element 5</li>
                <li>Element 6</li>
            </ul>
        </div>
 
        <div id="output"></div>
 
        <script type="text/javascript">
            function doSomething(item, i)
            {
                var output = $('output');
 
                if (i == 2)
                    return; // "continue"
 
                output.update(output.innerHTML + '<br />' + item.innerHTML);
 
                if (i == 3)
                    throw new $break;
            }
 
            $$('#foo li').each(doSomething);
        </script>
    </body>
</html>

In This Article