Tagged with downcasting

Q&A – is, as, and type conversion

by

A question from a reader gave me an excuse to write a huge rant about type conversions:

I’m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very useful, more of a teaching thing really. However there’s a bit of code that says:

var tf:TextField = event.target as TextField;

I don’t understand this at all! What the hell is event.target as TextField? Anyway here’s the full code for context’s sake:

package com.FoundationAS3.ch6 {

	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.events.TextEvent;

	public class PreventDefaultTest extends Sprite {

		public function PreventDefaultTest() {
			var tf:TextField = new TextField();
			addChild(tf);

			tf.width = stage.stageWidth;
			tf.height = stage.stageHeight;
			tf.type = TextFieldType.INPUT;
			tf.wordWrap = true;

			tf.addEventListener(TextEvent.TEXT_INPUT, onTextFieldTextInput);
		}

		private function onTextFieldTextInput(event:TextEvent):void {
			var tf:TextField = event.target as TextField;
			if (tf.text.indexOf(event.text) > -1) {
				event.preventDefault();
			}
		}
	}
}

Thanks,
-Neal

My response after the jump.
Continue reading

Tagged , , , , , , , ,