Prototype JS: Preventing the Default Action Without Stopping other Event Handlers

26/4/2010

When re-using web components in Tapestry 5, I sometimes end up having multiple client-side classes observing the same events on the same objects. For example, I have a button in a modal dialog that requires two event listeners: One dismisses the modal dialog (this is written as a Tapestry Mixin to a button or link), and one that executes custom client-side code specific to the dialog. For things to work, they must both execute, but the default action (e.g. following a link or submitting a form) must not take place.

Now here's the problem I had until a few minutes ago: In Prototype, I thougt the Event.stop() method was the only option -- however, it does not only stop the default behaviour, but, as its name suggests, immediately stops the propagation of the event. If you have two event listeners bound to the same event type and they both call Event.stop(), only one of the event listeners will execute.

I just accidently (while debugging some JS) found out that there is a standard way to prevent the default behaviour only without stopping the event altogether. It's called Event.preventDefault(), and it is not mentioned in the API docs because it's a standard method. (Note: IE does not support preventDefault(), but Prototype emulates it for IE).

Now I call Event.preventDefault() and see all my event listeners execute happily.

Comments