PhpRiot
Download This Article
Download this article or the entire “Eight Weeks of Prototype” series with all listings and files.




More information
Related Books
JavaScript: The Good Parts

JavaScript: The Good Parts

Most programming languages contain good and bad parts, but JavaScript has more than its share of...

ASP.NET AJAX in Action

ASP.NET AJAX in Action

Ajax has revolutionized the way users interact with web pages today. Gone are frustrating page...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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


Tagged in ,