2
votes

I want to call a function that is inside the root timeline of Flash from an external class.

This code is from the class:

private function loadImage(event:Event):void
{
    addToContainer()   
}

In the main timeline:

function addToContainer():void
{
    trace("Called")
} 

How to manage that?

4

4 Answers

2
votes

Do you need to put addToContainer() in the timeline?

I would consider removing your code entirely from the timeline, and creating a "Document class" with addToContainer in it instead. That makes it easier to keep track of what you're looking at.

public class FunctionTest extends MovieClip {
   protected static var _this:FunctionTest;
   function FunctionTest() { _this = this; }
   public static function get application_root():FunctionTest { return _this; }
   public function addToContainer():void { trace("Called"); }
}

Now you have two ways of writing loadImage. If it's within a DisplayObject (as per Marty Wallace's earlier comment), you can say something like

(this.root as FunctionTest).addToContainer();

If not, you have an alternative you can use from anywhere:

FunctionTest.application_root.addToContainer();

If you really have to define addToContainer() in the timeline, then you will need to initialize the external class with a link to the display root. Do something like:

public class LoadImageClass {
   protected var _stored_root:MovieClip;
   function LoadImageClass(new_root:MovieClip) { this._stored_root = new_root; }
   public function loadImage():void {
      this._stored_root.addToContainer();
   }
}
0
votes

Try to use

MovieClip(root)

to access the main timeline.

0
votes

You can add an event listener to your object in the main timeline. When this event is triggered on your object, your function in the main timeline will be called.

//Main Timeline
var obj:YourExternalClass = new YourExternalClass();

obj.addEventListener(MouseEvent.CLICK, addToContainer);
0
votes

The best and most simple way is to push the main timeline as a parameter in your class:

set a variable in your class:

public static var _this:Object;

now in your main timeline set this variable:

MyClass._this=this;

now in your class you have access to the main timeline using the _this variable:

_this.addToContainer()

I H☺P E this helps !