// site.fx.Dactylo package site.fx { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.text.TextFormat; import vegas.commands.IAsyncCommand; import vegas.events.CommandEvent; import flash.events.Event; import flash.text.TextField; import flash.utils.Timer; public class Dactylo extends EventDispatcher implements IAsyncCommand { private var __tf:TextField; private var __text:String; private var __letterPerIteration:int; private var __index:int; private var __timer:Timer; private var __tfAutoSize:String; private var __tfTextFormat:TextFormat; /** * Applies a typewriter animation on target textField */ public function Dactylo(tf:TextField, text:String, letterPerIteration:int = 1, tempoMs:Number = 50):void { __tf = tf; __tfAutoSize = __tf.autoSize; __tfTextFormat = __tf.getTextFormat(); __tf.text = ''; reset(text, letterPerIteration, tempoMs); } public function reset(text:String, letterPerIteration:int = 1, tempoMs:Number = 50):void { __text = text; __letterPerIteration = letterPerIteration; if (__timer == null){ __timer = new Timer(tempoMs, 0); __timer.addEventListener(TimerEvent.TIMER, render); } else{ endTimer(true); __timer.delay = tempoMs; __timer.repeatCount = Math.ceil(text.length / letterPerIteration); } } public function isRunning():Boolean { return __timer.running; } public function execute(e:Event = null):void { endTimer(true); __timer.start(); } private function endTimer(reset:Boolean = false):void { __timer.stop(); if (reset){ __index = 0; } } private function render(e:Event = null):void { if (__index > __text.length){ __tf.text = __text; endTimer(true); dispatchEvent(new CommandEvent(CommandEvent.COMPLETE)); } else{ __tf.text = __text.substr(0, __index); trace(__tf.text); __index += __letterPerIteration; } __tf.autoSize = __tfAutoSize; __tf.setTextFormat(__tfTextFormat); } } }