当前位置: > > > AS3 - addChild时,执行两次子对像的updateDisplayList()方法

AS3 - addChild时,执行两次子对像的updateDisplayList()方法

在Flex开发中遇到一个情况,就是在updateDisplayList()里面使用addChild添加子组件时,会执行两次子组件的updateDisplayList()方法。

比如:
<?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" >
	<fx:Script>
		<![CDATA[
			import mx.core.UIComponent;
			private var _CompContainer:UIComponent;
			
			override protected function createChildren():void{
				super.createChildren();
				_CompContainer = new UIComponent();
				this.addElement(_CompContainer);
			}
			override protected function updateDisplayList(unscaledWidth:Number,
														  unscaledHeight:Number):void{
				trace(this.className+":updateDisplayList()");
				super.updateDisplayList(unscaledWidth,unscaledHeight);
				
				_CompContainer.addChild(new ChildComp());
			}
		]]>
	</fx:Script>
</s:Application>

子对象组件:
package
{
	import mx.core.UIComponent;

	public class ChildComp extends UIComponent
	{
		override protected function commitProperties():void{
			trace(this.className+":commitProperties()");
			super.commitProperties();
		}
		
		override protected function updateDisplayList(unscaledWidth:Number,
													  unscaledHeight:Number):void{
			trace(this.className+":updateDisplayList()");
			super.updateDisplayList(unscaledWidth,unscaledHeight);
		}
	}
}

可以看到执行结果是:
 MainApplication:updateDisplayList()
 ChildComp:updateDisplayList()
 ChildComp:commitProperties()
 ChildComp:updateDisplayList() 

解决办法1:
_CompContainer.addChild(new ChildComp());
_CompContainer.validateNow();

解决办法2:
callLater(_CompContainer.addChild,[new ChildComp()]);
评论0