views:

330

answers:

1

I'm trying to migrate from using inline event triggers to using event listeners using Prototype's Event.observe function. There are a few inline commands that I don't know how to handle using the function call.

I want to move from:

<form id='formFoo' action='whatever.php' onsubmit="return Foo.verify(this);">

To an event call:

Event.observe('formFoo', 'submit', Foo.verify);

This of course will not work, as I need a return value from the function I call to determine whether the form gets submitted or not.

How do I do this using event handlers?

+2  A: 

The easiest way to do this is probably Event.Stop from prototype. This works for me (put this in any script block):

Foo = { verify: function(){ return false } };

Event.observe(window, 'load', function() {
    Event.observe('formFoo', 'submit', function(e){
        if(! Foo.verify($('formFoo'))){
            e.stop();
        }
    });
});

It stops every form submission; you will just have to change Foo.verify to do what you wanted.

Explanation: When the submit event is triggered, prototype passes the handler a prototype Event object representing the event, and the stop method on that object prevents the submit. The rest is just setting up the event.

Minor note: Among other things, passing Foo.verify directly as a handler will cause verify to be called as a function, not a method (this will be the global object within the call, rather than Foo). That situation might be okay - if verify doesn't use this, you're fine. Be aware of the difference, though.

Jesse Millikan
Unfortunately, this still allows the form to be submitted before the results of the verify function are returned. This works fine on a button (using click event), but this is a search form, and there is only one input, so if the user hits 'Enter', the form is submitted
Mike
You updated your answer while I was typing my response... the above works perfectly. Thanks for the explanation.
Mike
Click the little checkbox if you like it :)
Jesse Millikan