日期:2013-11-24  浏览次数:20846 次

在Flex1.5中,如果我们要实时创建一个组件实例的话,可以使用createChild()方法。
例如,假定以下代码在MyApp.mxml中:

   <mx:Script>
       import mx.controls.Button; 
       var stopButton:Button;

       function someEventHandler():Void
       {
           stopButton = Button(form1.createChild(Button, undefined, { label: "Stop!" }));
       }
   </mx:Script>

以上独一的方法同时完成下面四件事情:
创建特定类(Button)的一个实例(stopButton)。
使用“initObj({ label: "Stop!" })”设置该新实例的属性(label)。
将新创建的实例附加到一个父容器(form1)中。
为了与其他兄弟实例区分开,将该实例的_name属性设置为独一类似__Button17的字符串值。
实际上,在内部,createChild()调用的是MovieClip类的attachMovie()方法来完成实例的创建。

而在Flex2中,类似createChild()这样的方法将不再必须也不是恰当的方法,由于在Flash Player 8.5中,可以像创建其他对象一样使用new操作来创建可视对象,并且,当一个可视对象实例创建后,其是没有父组件的,我们可以将其添加到父容器中,也可以在随后将其移除并添加到其他的父容器中(是的,Flash终于支持re-parenting),或者,我们可以将其移除以让其被垃圾回收器回收。

新的动态实时创建实例的方法如下:

       import mx.controls.Button;
       var stopButton:Button; 
       function someEventHandler():Void
       {
           stopButton = new Button();
           stopButton.label = "Stop!";
           stopButton.setStyle("color", 0xFF0000);
           form1.addChild(stopButton);
       }

以上使用了更多行的代码,但是他愈加的清晰而易于理解:

使用new操作符创建一个新的实例。
使用普通的赋值语句和setStyle()方法设置该新实例的属性和款式。
显式调用addChild()方法将该新的实例添加到父组件中。
留意:其他的API,如:destroyChild()、destroyChildAt()及destroyAllChildren()方法以及被移除,替代他们的是:removeChild()、 removeChildAt()和removeAllChildren()方法。

最后,请记住以下Flex2中组件创建的周期:
创建(new) - add添加(add) - 移除(remove) - ( 添加 - 移除 - ... ) - 被垃圾收集
原文地址:Creating Component Instances at Runtime
另外,今天才知道,原来Flash Player 8.5的开发代号叫:Zaphod
PS:Firefox的查看选中部分源代码的功用真是方便,IE有的学哦...:)