Posts Tagged ‘as’

AS3 “with” keyword and casting

Monday, July 12th, 2010

I’ve rarely (if ever) used the “with” keyword in as3, but I recently found a neat trick to use it with.

When I quickly need to cast an object to access a few methods/properties I don’t always want to
create a new casted variable:

var child:DisplayObject = getChildThatMightBeMovieClip();

if (child is MovieClip) {
	var childAsMc:MovieClip = child as MovieClip;
	trace(childAsMc.numChildren);
	trace(childAsMc.currentFrame);
}

or cast it every single time:

var child:DisplayObject = getChildThatMightBeMovieClip();

if (child is MovieClip) {
	trace((child as MovieClip).numChildren);
	trace((child as MovieClip).currentFrame);
}

Using the “with” keyword, we can temporarily cast it without creating a temporary casted variable or casting it again and again:

var child:DisplayObject = getChildThatMightBeMovieClip();

if (child is MovieClip) {
	with (child as MovieClip) {
		trace(numChildren);
		trace(currentFrame);
	}
}

Elegant =)

Global error handling with Flash Player 10.1

Wednesday, June 23rd, 2010

Since the official release of Flash Player 10.1 is out, now might be a good time to start implementing the global error handler.

When this is written, flash builder 4 doesn’t have a native way that lets you use it, so we have to do a little mix. (Update: The update is out.)
The global error handler works by adding an event to the uncaughtErrorEvents property of the loaderInfo of the application.
There are currently two methods of getting it to work.

Method 1 – The backwards compatible one:

Here the code doesn’t crash in flash player 9/10, but the error handling will only work in 10.1.

if(loaderInfo.hasOwnProperty("uncaughtErrorEvents")){
	IEventDispatcher(loaderInfo["uncaughtErrorEvents"]) .addEventListener("uncaughtError", uncaughtErrorHandler);
}
private function uncaughtErrorHandler(e:Event):void {
	trace("Global error:", e);
}

Method 2 – The type safe one:

Get the Flex 4.1 SDK if you haven’t already and choose that one as your project’s SDK.

Now you can use the new global error handling like it was meant to be used:

import flash.events.UncaughtErrorEvent;

loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);

private function uncaughtErrorHandler( e:UncaughtErrorEvent):void {
	trace("Global error:", e);
}