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
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.
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
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
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.
2for the third iteration and
3for the fourth iteration.