flex组件在建立的时候都会经历四个事件:preinitialize, initialize, creationComplete和updateComplete (updateComplete事件在任何改动视觉的情况下都会发生,不是初始化时独有的)。我这里有个例子来检测在嵌套和平行的情况下,测试各个组件的事件抛出顺序。
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" preinitialize="showEvent(event)" initialize="showEvent(event)" creationComplete="showEvent(event)" updateComplete="showEvent(event)"> <mx:Script> <![CDATA[ import flash.utils.getTimer; private function showEvent(event:Event):void { trace(flash.utils.getTimer().toString()+" >> "+ event.currentTarget.name+" "+event.type); } ]]> </mx:Script> <mx:Canvas id="canv1" preinitialize="showEvent(event)" initialize="showEvent(event)" creationComplete="showEvent(event)" updateComplete="showEvent(event)"> <mx:Button id="btn1" preinitialize="showEvent(event)" initialize="showEvent(event)" creationComplete="showEvent(event)" updateComplete="showEvent(event)"/> </mx:Canvas> <mx:Button id="btn2" preinitialize="showEvent(event)" initialize="showEvent(event)" creationComplete="showEvent(event)" updateComplete="showEvent(event)"/> </mx:Application>
输出是:
1299 >> eventTest0 preinitialize 1307 >> canv1 preinitialize 1310 >> btn1 preinitialize 1318 >> btn1 initialize 1319 >> canv1 initialize 1320 >> btn2 preinitialize 1321 >> btn2 initialize 1321 >> eventTest0 initialize [SWF] G:\projects\eventTest\bin-debug\eventTest.swf - 588,818 bytes after decompression 1387 >> btn1 creationComplete 1387 >> btn1 updateComplete 1387 >> canv1 creationComplete 1387 >> canv1 updateComplete 1388 >> btn2 creationComplete 1388 >> btn2 updateComplete 1388 >> eventTest0 creationComplete 1390 >> eventTest0 updateComplete
看着有点混乱,不过仔细看看,可以把过程分成两个部分。很明显,所有的creationComplete和updateComplete发生在第二次update的时候,之前flex组件只是做一些设置和计算的工作,并没有在画布上画任何东西。除此以外,还有这么一些规律:
* 就单个组件而言,事件的抛出顺序是preinitialize ,initialize ,creationComplete
* 嵌套关系的两个组件(比如Canvas和button1),preinitialize 先外后内 ,initialize和creationComplete 先内后外 。只是creationComplete 要在下一次update才会发生 。
* 平行关系的两个组件(比如Canvas和button2),按mxml内的顺序,只有前面组件initialize结束后,后面的组件才会抛出preinitialize。