At the Forge - Prototype

Prototype eases the burden of using JavaScript in Ajax.

The $() function is more than merely a terse replacement for document.getElementById(). If we hand it multiple IDs, it returns an array of nodes with those IDs. For example, we can add a second headline and then set them both with the following code:

function setHeadline() {
    var headlines = $("headline", "empty-headline");

        for (i=0; i<headlines.length; i++)
        {
            Element.update(headlines[i], $F("field1"));
        }
}

Whereas there is only text in the headline node when the page is loaded, pressing the button results in setting both headline and empty-headline to the contents of the field1 field.

Doing More with Prototype

Prototype brings much more to the table than $(), $F() and a few convenience classes. You can think of it as a grab-bag of different utility functions and objects that make JavaScript coding easier.

For example, in our above definition of setHeadline, we had the following loop:

for (i=0; i<headlines.length; i++)
{
    Element.update(headlines[i], $F("field1"));
}

This should look familiar to anyone who has programmed in C, Java or Perl. However, modern programming languages (including Java) often support enumerators or iterators, for more expressive and compact loops without an index variable (i, in the above loop). For example, this is how we can loop over an array in Ruby:

array_of_names = ['Atara', 'Shikma', 'Amotz']
array_of_names.each do |name|
    print name, "\n"
end

Prototype brings Ruby-style loops to JavaScript, by defining the Enumerator class and then providing its functionality to the built-in Array object. We thus could rewrite our setHeadline function as:

function setHeadline() {
    var headlines = $("headline", "empty-headline");

        headlines.each(
            function(headline) {
                Element.update(headline, $F("field1"));
            }
        );
}

This code might look a bit odd, half like Ruby and half like JavaScript. In addition, it might seem strange for us to be defining a function inside of a loop, which is itself executing inside of a function. However, one of the nice features of JavaScript, like many other modern high-level languages, is that functions are first-class objects, which we can create and pass around exactly like any other type of object. Just as you wouldn't be nervous about creating an array inside of a loop, you shouldn't be nervous about defining a function inside of a loop.

I should also note that the each method provided by Prototype's Enumerated object takes an optional index argument, which counts the iterations. So, we can say:

function setHeadline() {
    var headlines = $("headline", "empty-headline");

        headlines.each(
            function(headline, index) {
                Element.update(headline, index + " " + $F("field1"));
            }
        );
}

Now, each headline will appear as before, but with a number prepended to the text. Listing 3 shows the resulting page.

Prototype provides additional methods for Enumerable objects, such as all find (to locate an object for which a function returns true); inject (to combine the items using a function, useful for summing numbers); min/max (to find the minimum or maximum value in a collection); and map (to apply a function to each member of a collection). These methods are available not only for arrays, but also for Hash and ObjectRangle, two classes that come with Prototype.

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState