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 4, Event Handling in Prototype

Observing Events

In order to use Prototype to handle events, the key method to use is observe().This method is one of the element extensions added by Prototype (as we saw in part 2 of this series). This means you can call observe() directly on the element on which you wish to observe an event, or you can pass that element as the first argument to Event.observe().

Listing 2 demonstrates the two different ways of observing an event on the same element. Note that in both cases we are using the $() function which you should now be familiar with (covered in the first article of this series). I've included some basic event handlers in this example: try hovering your mouse over the text or clicking on the text.

Listing 2 Two different ways of observing an event on an element (listing-2.html)
<html>
    <head>
        <title>Two different ways of observing an event on an element</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo">
            This is the element to observe
        </div>
 
 
        <script type="text/javascript">
            var elt = $('foo');
 
            Event.observe(elt, 'mouseover', function() {
                $('foo').setStyle({ backgroundColor : '#fc0' });
            });
 
            elt.observe('click', function() {
                alert('Click 2');
            });
 
            elt.observe('mouseout', function() {
                $('foo').setStyle({ backgroundColor : '' });
            });
        </script>
    </body>
</html>

The most important concept to take from this example is that you can use either Event.observe(elt, ...) or elt.observe(...). In order to observe events on the page as a whole (that is, with the window object), you must use Event.observe().

This is demonstrated in Listing 3, where an alert box is shown once the page completes its loading. This code is the "correct" way to do what is done in Listing 1. That is, rather than using <body onload="..."> or window.onload, we use Prototype's observe() method.

Listing 3 Checking for page load completion (listing-3.html)
<html>
    <head>
        <title>Checking for page load completion</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            Event.observe(window, 'load', function() {
                alert('Page has loaded!');
            });
        </script>
    </body>
</html>

Now that you know the two different ways of invoking observe(), let's look at the other arguments passed to this method. Firstly, the name of the event is passed. You may have noticed from listings 3 and 4 that on is omitted from the event name. That is, if you wanted to observe the onclick event you would pass click as the argument. Technically click is what happened (the event), and onclick is what happens when the click occurs.

The final argument passed to observe() is the function you want to execute when the event is triggered. We will look more in depth at how to write these functions in the next section.

As usual, you can pass either a function pointer, or define the function there and then. Listing 4 shows you these different ways of defining the event handler function.

Listing 4 Two different ways of defining event handlers (listing-4.html)
<html>
    <head>
        <title>Two different ways of defining event handlers</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo">
            Click me!
        </div>
 
        <script type="text/javascript">
            // method 1: defining the function inline
            Event.observe(window, 'load', function() {
                alert('Page has loaded!');
            });
 
 
            // method 2: defining the function then passing its name to observe()
 
            function handleFooClick()
            {
                alert('I was clicked!');
            }
 
            $('foo').observe('click', handleFooClick);
        </script>
    </body>
</html>

In general (and this is typically true for all JavaScript code you write), it's better to define the function separately from the call to observe(). This is because your code becomes much easier to maintain when done in this way. You will especially see how this helps in the sixth article of this series (when I show you how to write classes with Prototype).

In some rare cases I will define an event handler inline if it is performing some extremely trivial functionality.

In This Article