tags:

views:

31

answers:

1

Hi, can someone help me understand this because it's working in as3 but not so much in flex and I really can't seem to get my head around it. I can get it working by changing my function to static but I don't want to do this.

Ok so first I've created a package

package testPackage
{
public class TestClass
{
    public function TestClass()
    {       
    }

    public function traceName(str:String):void
    {
        trace(str);
    }       
}
}

and then I'm trying to import that package and create a class from that

import testPackage.TestClass;

var getClass:TestClass = new TestClass();
getClass.traceName("hello");

But I keep getting the error Access of undefined property getClass

+1  A: 

You're most likely putting the new TestClass() statements directly in the <fx:Script> tag body.

That doesn't work like that in Flex.

The <fx:Script> tag should contain only import statement, variables & functions definitions. No direct runtime code.

You need to put your class initialisation code in one of the flex event handler.. You could start with the application's applicationComplete event handler.

Like so

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="creationCompleteHandler(event)"
               >
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import testPackage.TestClass;

            // This doesn't work here
            // var getClass:TestClass = new TestClass();
            // getClass.traceName("hello");


            protected function creationCompleteHandler(event:FlexEvent):void
            {
                // it works here
                var getClass:TestClass = new TestClass();
                getClass.traceName("hello");
            }

        ]]>
    </fx:Script>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
</s:Application>
Ben