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

Stopping Observation

There are some cases where you will only want to observe an event for a period of time. That is, you want to remove the event handler after some condition is met. To do this, the stopObserving() method should be used.

Just like when using observe(), you can call this method directly on an element, or use Event.stopObserving() and pass the element in question as the first argument. While it doesn't really matter which way you do it, for code consistency you should do it the same as you did when calling observe() initially.

To successfully stop observing the event, you must pass the same arguments to stopObserving() as you did when you called observe(). That is, you must pass the event name and the name of the callback function.

Note: This is another good argument for not defining an anonymous function inline when observing the event. If you do so, you will be unable to stop observing the event since you can't reference this function any more.

Listing 14 shows an example of stopping the observation of an element. In this example, when you click the element an alert box is shown confirming that the event occurred. At this point in the code, the click event is no longer observed, meaning if you click the element again the alert box will no longer be shown.

Listing 14 Stopping the observation of an event using stopObserving() (listing-14.html)
        <title>Stopping the observation of an event using stopObserving()</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
        <div id="foo">
            Click me
        <script type="text/javascript">
            function onFooClick(e)
                var element = Event.element(e);
                alert('You clicked the element!');
                element.stopObserving('click', onFooClick);
                element.update('Clicking me now does nothing');
            $('foo').observe('click', onFooClick);

In This Article