PDA

View Full Version : Converting keydown listener to Ext, return false, alerts...



emkman
27 Nov 2007, 10:13 AM
I am converting a keydown listener which disallows most keys to be pressed in a file upload input.

Here is the old code:


function mustBrowse(e)
{
var code;
if (!e) var e = window.event;
code = e.keyCode ? e.keyCode : e.which;
if (code != 9 && code != 32 && code!= 8 && code != 46) return false;
}


Here is the new code which works:


function mustBrowse(e)
{
var code = e.getKey();
if (code != 9 && code != 32 && code!= 8 && code != 46) e.stopEvent();
}

The new normalized code is cleaner, but I ran into a few issues along the way.
My questions are:

What is the equivalent to return false? e.stopEvent(), e.preventDefault(), or neither?
The function breaks and all keys make it through if there is an alert() in the function. Why is that? Even if the alert is after e.stopEvent()! Can this be prevented?


Thanks for the help.

hendricd
27 Nov 2007, 1:03 PM
stopEvent() prevents the event from further bubbling in the DOM, not stop execution of your event handler.



function mustBrowse(e)
{
var code = e.getKey();
if (code != 9 && code != 32 && code!= 8 && code != 46){
e.stopEvent();
return false;
}
}

emkman
27 Nov 2007, 1:26 PM
stopEvent() prevents the event from further bubbling in the DOM, not stop execution of your event handler.


I think you are confusing stopEvent() with stopPropagation(). stopEvent() combines stopPropagation() and preventDefault(). From the api:

stopPropagation() : void
Cancels bubbling of the event.

stopEvent() : void
Stop the event (preventDefault and stopPropagation)


I could probably use return false instead of stopEvent(). It wasn't working before, but that is when I had the alert() added in for debugging, which is the real issue I am wondering about.