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.

______________________

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix