Eight Weeks of Prototype: Week 4, Event Handling in Prototype
Stopping an Event
Frequently you will want to stop an event from completing, since you are defining a method by which to handle the event, and therefore don't want the browser to use its own handling method.
The two best examples of this are for hyperlinks and forms. Firstly, let's look at links. Often you will want to perform some action when the user clicks a link, however you don't want the browser to follow the link.
Before using Prototype, you might be more familiar with returning
false from the event handler. For example, you might use
<a href="..." onclick="doSomething(); return false">...</a>. By returning
false in the
onclick handler, the browser knows not to follow the link in the
In order to achieve this same effect with Prototype, the
Event.stop() method is used instead. Returning
false from your handler method will have no effect. Calling
Event.stop() tells Prototype to stop event propagation and not perform the default browser action.
Event.stop()in any or all the handlers. I'll cover this in more detail shortly.
OK, then the link is followed, whereas clicking
Cancel will result in the link not being followed.
submit event, you can then check form values before deciding whether or not to allow the browser to submit the form.
Listing 7 shows an example of how this is achieved. In this example, I've created a form with a single text input. The validation routine (
onFormSubmit()) checks if this text input is blank (we covered the
blank() method in the third article of this series), and if so records an error.
To complete the event handler, we check if there are any errors (by checking the size of the errors array), and if so we stop the event from propagating and display an error message.
trueis not passed as the first argument then the data is returned as a "get" style string (which is difficult for us to validate).
Technically you could observe the
click event on the submit button rather than the
submit event on the form, however the form might be submitted using a method other than this button. For instance, if the user presses enter while filling out the text input the form will be submitted (triggering the
submit event but not the button