开发者

Return Functions using prototype's Event.observe

I'm trying to migrate from using inline event triggers to using event list开发者_StackOverfloweners 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜