在 ActionScript 中动态创建 Flex 组件 [英] Dynamically Creating Flex Components In ActionScript

查看:28
本文介绍了在 ActionScript 中动态创建 Flex 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

难道没有什么方法可以重写下面的代码,这样我就不需要每个可以想象的类型的巨大的 switch 语句吗?另外,如果我可以用某种方式替换 switch 语句来动态创建新控件,那么我可以使代码更小、更直接,并且不必预测自定义控件类型的可能性.

Isn't there some way to re-write the following code, such that I don't need a gigantic switch statement with every conceivable type? Also, if I can replace the switch statement with some way to dynamically create new controls, then I can make the code smaller, more direct, and don't have to anticipate the possibility of custom control types.

之前:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="vertical">
  <mx:Script>
    <![CDATA[
      import mx.containers.HBox;
      import mx.controls.Button;
      import mx.controls.Label;
      public function CreateControl(event:Event):void {
        var Type:String=Edit.text;
        var NewControl:Object;

        switch (Type) {
          case 'mx.controls::Label':NewControl=new Label();break;
          case 'mx.controls::Button':NewControl=new Button();break;
          case 'mx.containers::HBox':NewControl=new HBox();break;
          ... every other type, including unforeseeable custom types
        }

        this.addChild(NewControl as DisplayObject);
      }
    ]]>
  </mx:Script>
  <mx:Label text="Control Type"/>
  <mx:TextInput id="Edit"/>
  <mx:Button label="Create" click="CreateControl(event);"/>
</mx:WindowedApplication>

之后:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" 
  layout="vertical">
  <mx:Script>
    <![CDATA[
      import mx.containers.HBox;
      import mx.controls.Button;
      import mx.controls.Label;
      public function CreateControl(event:Event):void {
        var Type:String=Edit.text;

        var NewControl:Object= *???*(Type);

        this.addChild(NewControl as DisplayObject);
      }
    ]]>
  </mx:Script>
  <mx:Label text="Control Type"/>
  <mx:TextInput id="Edit"/>
  <mx:Button label="Create" click="CreateControl(event);"/>
</mx:WindowedApplication>

推荐答案

看看 flash.utils.getDefinitionByName().

Take a look at flash.utils.getDefinitionByName().

我还没有运行过这段代码,但你应该能够按照

I haven't run this code, but you should be able to do something along the lines of

public function CreateControl(event:Event):void {
    var Type:String=Edit.text;
    var controlClass:Class = getDefinitionByName(Type) as Class;

    var NewControl:Object= new controlClass();

    this.addChild(NewControl as DisplayObject);
}

这篇关于在 ActionScript 中动态创建 Flex 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆