Flash构建器访问未定义的属性问题

时间:2012-03-25 21:43:49

标签: actionscript-3 flash-builder

我正在尝试运行以下简单代码:

<fx:Script>
        <![CDATA[

        import flash.display.*;
        import flash.net.URLRequest;


        var url2:String = "image2.jpg";
        var urlRequest:URLRequest = new URLRequest(url2);   //problem code
        var loader:Loader = new Loader();     //problem code
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);   //problem code
        loader.load(urlRequest);
        addChild(loader);

        function loader_complete(evt:Event):void {
            var target_mc:Loader = evt.currentTarget.loader as Loader;
            target_mc.x = (stage.stageWidth - target_mc.width) / 2;
            target_mc.y = (stage.stageHeight - target_mc.height) / 2;
        }
    ]]>
</fx:Script>

然而,我说错误

'access of undefined property 'loader_complete'
'access of undefined property 'loader'
'access of undefined property 'loader'
'access of undefined property 'loader'
'access of undefined property 'urlReguest'

我暂时没有使用Flash构建器,需要一些助手。有什么想法吗?谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您正在尝试在类定义中执行代码。

应该从一个函数调用可执行代码,例如在Flex组件生命周期中创建完成:

<?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"
               creationComplete="creationCompleteHandler(event)">


    <fx:Script>
        <![CDATA[
            import flash.display.*;
            import flash.net.URLRequest;

            import mx.events.FlexEvent;

            public var url2:String = "image2.jpg";
            public var urlRequest:URLRequest = new URLRequest(url2); //problem code
            public var loader:Loader = new Loader(); //problem code

            protected function creationCompleteHandler(event:FlexEvent):void
            {
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete); //problem code
                loader.load(urlRequest);
                addChild(loader);
            }

            protected function loader_complete(evt:Event):void
            {
                var target_mc:Loader = evt.currentTarget.loader as Loader;
                target_mc.x = (stage.stageWidth - target_mc.width) / 2;
                target_mc.y = (stage.stageHeight - target_mc.height) / 2;
            }
        ]]>
    </fx:Script>


</s:Application>