3
votes

I'm trying to prevent any key from altering the text in a Flex TextArea. I don't want to set the editable property to false, because I want the caret to be visible for a 'current position' indicator, so that the user knows where a search he initiates will start from.

I've added event handlers for change and textInput, as well as keyUp and keyDown that do an 'event.preventDefault' as well as a 'event.stopImmediatePropagation'. This works just fine for most keys, with the exception of backspace and delete.

Is there any way to prevent these from doing anything ?

4
In your event listeners where you preventDefault and stopPropagation are you using the capture phase?JD Isaacks

4 Answers

1
votes

Hmmm, seems like it really doesn't work in the browser, how about a workaround, not sure if you'll like it but seems to be achieving what you need apart from pasting:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private var _lastSelStart:Number = 0;
            private var _lastSelEnd:Number = 0;
            private var _lastText:String = null;
            private var _prevent:Boolean = false;

        private function onKeyDown(event:KeyboardEvent):void {
            if ( event.keyCode == 8 || event.keyCode == 46 ) {
                if ( !_prevent ) {
                    _prevent = true;
                    _lastText = txt.text;
                    _lastSelStart = txt.selectionBeginIndex;
                    _lastSelEnd = txt.selectionEndIndex;
                }
            }
        }

        private function onKeyUp( event:KeyboardEvent ):void {
            if ( _prevent ) {
                _prevent = false;
                txt.text = _lastText;
                _lastText = null;
                callLater(txt.setSelection, [_lastSelStart, _lastSelEnd]);
            }
        }

        ]]>
    </mx:Script>
    <mx:TextArea keyDown="onKeyDown(event);" keyUp="onKeyUp(event);" width="100%" height="100%"
        id="txt" />
</mx:Application>
2
votes

This may help:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            private function onKeyDown(event:KeyboardEvent):void {
                if ( event.keyCode == 8 || event.keyCode == 46 ) {
                    event.preventDefault();
                }
            }
    ]]>
    </mx:Script>
    <mx:TextArea keyDown="onKeyDown(event);" width="100%" height="100%" />
</mx:WindowedApplication>
1
votes

Why not just reinsert the text on change?

0
votes

I think I've figured out a way: in flash the preventDefault don't work for key event, but they work well for changing event. You can do something similar to this https://stackoverflow.com/a/8078910/1927950 to avoid any modification but still keep the caret.