Skip to content


Target the Main Document Class from an object not on the Active Display List

So I ran into an issue where I needed to call a function within the Document Class file from another file that did not reside within the active display list. If the object is on the active display list you can simply use:

DocumentClassName(root).function();

But since the object is no on the active display list please check out the code below:

Here is the Document Class – Main.as

package {
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.display.DisplayObject;
	import fl.controls.TextArea;
	import fl.controls.ScrollPolicy;

	public class Main extends Sprite
	{
		// claim the stage
		public static var stage:Stage;
        public static var root:DisplayObject;

		//text area component
		private var output:TextArea;

		public function Main()
		{
			// build the UI
			ShowOutput();

			// setup stage
			Main.stage = this.stage;
			Main.root = this;

			// add the class
			var MC:MainClass = new MainClass();
			addChild ( MC );
		}

		public function traceOut():void
		{
			Message ( "This function is called from the SubClass.as file" );
		}

		/*
		FOR DISPLAY OF OUTPUT
		============================================================
		*/
		private function ShowOutput():void
        {
			output = new TextArea();
			output.verticalScrollPolicy = ScrollPolicy.ON;
			output.condenseWhite = true;
			output.setSize(stage.stageWidth, 300);
			output.move(0, 0);
			addChild(output);
        }

		public function Message(msg:String):void
		{
			output.appendText ( "\n" + msg );
		}
	}
}

MainClass.as file:

package
{
	import flash.display.Sprite;

	public class MainClass extends Sprite
	{
		public function MainClass()
		{
			var SC:SubClass = new SubClass;
			addChild ( SC );
		}
	}
}

SubClass.as

package
{
	import flash.display.Sprite;

	public class SubClass extends Sprite
	{
		public function SubClass()
		{
			// Call the function in the Main Document Class
			Main(Main.root).Message ( "This is the value if you use Main(root) = " + Main(root) );
			Main(Main.root).traceOut ();
		}
	}
}

Posted in Actionscript 3.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.