Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flex 3 accessing main mxml from actionscript code

im writting an actionScript class to handle my web service calls. When i retrieve a result i want to call a setter method in my main mxml application. My problem is that i dont know how to access the methods in the actionScript section of my main mxml class from my actionscript class, any ideas?

like image 388
cdugga Avatar asked Dec 10 '22 22:12

cdugga


1 Answers

David is right -- while you can access the public members of your Application.mxml object statically and from anywhere in your application, design-wise that's a bit of a no-no. It's better to strive for loose coupling between your objects, and the way that's done in the Flex idiom is generally to extend EventDispatcher and to dispatch events. So for example, your WebService wrapper might look something like this:

public class MyWrapperClass extends EventDispatcher
{
    [Event(name="webserviceComplete", type="flash.events.Event")]

    public function MyWrapperClass(target:IEventDispatcher=null)
    {
        super(target);
    }

    private function handleWebServiceLoadComplete(event:ResultEvent):void
    {
        dispatchEvent(new Event("webserviceComplete"));
    }

    public function doWork():void
    {
        // Load the service, etc., and ultimately call handleWebServiceLoadComplete()...
    }       
}

... and your Main.mxml file like this:

<mx:Script>
    <![CDATA[

        private function app_creationComplete(event:Event):void
        {
            var myWrapper:MyWrapperClass = new MyWrapperClass();
            myWrapper.addEventListener("webserviceComplete", mywrapper_webServiceComplete, false, 0, true);
            myWrapper.doWork();
        }

        private function mywrapper_webServiceComplete(event:Event):void
        {
            // Do the work you would've otherwise done in the public method
        }

    ]]>
</mx:Script>

In this case, the end result is the same -- completing the web-service load triggers the function in Main.mxml. But notice how mywrapper_webServiceComplete() is declared privately -- it's not called directly by MyWrapperClass. Main.mxml simply subscribes (with addEventListener()) to be notified when MyWrapperClass is finished doing its work, and then does its own work; MyWrapperClass knows nothing about the details of Main.mxml's implementation, nor does Main.mxml know anything about MyWrapperClass other than that it dispatches a webserviceComplete event, and exposes a public doWork() method. Loose coupling and information hiding in action.

Good luck!

like image 110
Christian Nunciato Avatar answered Dec 19 '22 15:12

Christian Nunciato