PhpRiot
Download 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...

jQuery: Novice to Ninja

jQuery: Novice to Ninja

jQuery: Novice to Ninja is a compilation of best-practice jQuery solutions to meet the most...
PhpRiot Newsletter
Your Email Address:

More information

Eight Weeks of Prototype: Week 4, Event Handling in Prototype

This article is part of the series “Eight Weeks of Prototype”. Eight Weeks of Prototype is a series of articles covering the most important aspects of JavaScript development with the Prototype framework. Prototype is a JavaScript framework used to help developers easily create powerful web applications that work across all modern web browsers.. Read more about Eight Weeks of Prototype...

Introduction

One of the most useful and important aspects of JavaScript developments is that of event handling. Prototype simplifies this process by providing a number of helpful methods for doing so. In this, the fourth article of "Eight of Weeks of Prototype", we will look at how Prototype helps with handling events.

In addition to the native events (such as onclick or onmouseover), I will also show you how to observe and handle custom events, which can help you dramatically when developing your Prototype-based JavaScript.

Aside from the useful helper methods provided by Prototype, there is another excellent reason for using Prototype to handle the events. By using Prototype, you can ensure that you don't write over existing event handlers.

To demonstrate this, look at the code in Listing 1. Based on this code, do you know which message will appear? This situation can occur when you use third-party libraries over which you have no control.

Listing 1 Demonstrating event handling ambiguity (listing-1.html)
<html>
    <head>
        <title>Demonstrating event handling ambiguity</title>
        <script type="text/javascript">
            window.onload = function() {
                alert('Message 1');
            }
        </script>
    </head>
    <body onload="alert('Message 2')">
 
    </body>
</html>

When using the observe() method provided by Prototype (which we will cover shortly), this problem does not arise, since Prototype will automatically append the new event handler to the existing handlers.

In This Article