diff --git a/src/as/com/threerings/flash/KeyRepeatBlocker.as b/src/as/com/threerings/flash/KeyRepeatBlocker.as new file mode 100644 index 00000000..bdc211ba --- /dev/null +++ b/src/as/com/threerings/flash/KeyRepeatBlocker.as @@ -0,0 +1,58 @@ +package com.threerings.flash { + +import flash.events.EventDispatcher; +import flash.events.IEventDispatcher; + +import flash.events.KeyboardEvent; + +import flash.utils.Dictionary; +import flash.utils.getTimer; // function import + +/** + * A very simple class that adapts the KeyboardEvents generated by some source by discarding + * the extra KEY_DOWN events generated while a key is held down. + */ +public class KeyRepeatBlocker extends EventDispatcher +{ + /** + * Create a KeyRepeatBlocker that will be blocking key repeat events from + * the specified source. + */ + public function KeyRepeatBlocker (source :IEventDispatcher) + { + _source = source; + + _source.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown); + _source.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp); + } + + /** + * Dispose of this KeyRepeatBlocker. + */ + public function shutdown () :void + { + _source.removeEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown); + _source.removeEventListener(KeyboardEvent.KEY_UP, handleKeyUp); + } + + protected function handleKeyDown (event :KeyboardEvent) :void + { + if (!_down[event.keyCode]) { + _down[event.keyCode] = true; + dispatchEvent(event); + } + } + + protected function handleKeyUp (event :KeyboardEvent) :void + { + delete _down[event.keyCode]; + dispatchEvent(event); + } + + /** Our source. */ + protected var _source :IEventDispatcher; + + /** Tracks whether a key is currently being held down. */ + protected var _down :Dictionary = new Dictionary(); +} +}