getDefinitionByName, ReferenceError and the Frame metadata tag

Posted by Dennis on Aug 21, 2009 in ActionScript, Flex1 comment

The hard-working, unstoppable Meister Wanja came to me with the following problem involving getDefinitionByName and interfaces. Say you have the following class:


package {
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;

	public class Blah extends Sprite
	{
		public function Blah()
		{
			var ref : String = "YourMama";
			var ClassRef : Class = getDefinitionByName( ref ) as Class;

			var booh : IMama = new ClassRef();
		}
	}
}

Build it, run it and the following error will be slapped in your face like a raw fish:


ReferenceError: Error #1065: Variable YourMama is not defined.
	at global/flash.utils::getDefinitionByName()
	at Blah()[C:\_webroot\Blah\src\Blah.as:10]

Adding the class as an import won’t work, the compiler won’t compile classes that are not used. One solution is to add an unused variable:


package {
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;

	public class Blah extends Sprite
	{
		public function Blah()
		{
			var unused : YourMama;
			var ref : String = "YourMama";
			var ClassRef : Class = getDefinitionByName( ref ) as Class;

			var booh : IMama = new ClassRef();
		}
	}
}

Or you can actually just reference the class like this:


package {
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;

	public class Blah extends Sprite
	{
		public function Blah()
		{
			YourMama;
			var ref : String = "YourMama";
			var ClassRef : Class = getDefinitionByName( ref ) as Class;

			var booh : IMama = new ClassRef();
		}
	}
}

Another solution is to add a Frame metadata tag to the class with the “YourMama” class specified in the extraClass attribute:


package {
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;

	[Frame(extraClass="YourMama")]

	public class Blah extends Sprite
	{
		public function Blah()
		{
			var ref : String = "YourMama";
			var ClassRef : Class = getDefinitionByName( ref ) as Class;

			var booh : IMama = new ClassRef();
		}
	}
}

This Frame metadata tag is an undocumented feature of the Flex compiler. More info can be found on this page: http://nondocs.blogspot.com/2007/04/metadataframe_22.html. This blog, “The Flex Non-Docs” is very interesting by the way :-)

There is ofcourse also the option to use the “includes” compiler argument. Personally, I prefer the use of the Frame tag.



Tags: ,


1 comment

» Comments RSS Feed
  1. Doesn’t specifying the missing class defeat the whole purpose of dynamic instantiation?!

Leave a comment