mimic
mimic

Reputation: 5224

How to call some mxml function from class?

I have 2 files: Main.mxml with application and one MyObject.as. I create the instance of MyObject in mxml and can call its every public function from mxml. But what if for some reason I need to call some function declared in mxml from MyObject class? How to do that? I thought that I could pass the reference to main.mxml class into this object but I couldn't figure out what exact class is it (it inherits Application, right, but what exact class is it?)

Thanks

Upvotes: 0

Views: 1377

Answers (2)

merv
merv

Reputation: 77098

If you are instantiating the MyObject class in your Main.mxml, you could also accomplish access to a method in Main by passing the method as a Function into the object.

Suppose you have in Main.mxml the function:

private function doSomething():*{
  ...
}

With an appropriate setter in MyObject.as:

private var _mainFunction:Function;

public function set mainFunction(f:Function):void
{
    _mainFunction = f;
}

Then you can pass the method when you instantiate the MyObject class in the mxml:

<*:MyObject mainFunction='doSomething'/>

And now you just call _mainFunction in the MyObject.as code whenever you need it.

Of course, Weltraumpirat's suggestion would be more efficient if you needed to access more than one method and/or variable on your Application.

Upvotes: 0

weltraumpirat
weltraumpirat

Reputation: 22604

It is of type Main (it takes on the name of the mxml file). You can add a static variable and getter method to it:

private static var _instance : Main;

public static function get instance () : Main {
    return _instance;
}

Then let instance refer to this after the application is complete:

private function applicationCompleteHandler():void
{
    _instance = this;
}

Don't forget to set applicationComplete="applicationCompleteHandler" in your <mx:Application> tag. After that you can call Main.instance from anywhere in your program to access the methods and variables.

Upvotes: 3

Related Questions