例如,我想在添加到舞台上添加的每个BorderContainer中添加标签子。类似:
// called on application preinitialize
private function preInit():void{
systemManager.stage.addEventListener(Event.ADDED, onElementAdded);
}
protected function onElementAdded(event:Event){
trace(event.target);
if(event.target && event.target is BorderContainer){
var label:Label = new Label();
label.text = "This is BorderContainer";
label.x = 10;
label.y = 10;
(event.currentTarget as BorderContainer).addElement(label);
}
}
但是我所追踪的一切都是:
mouseCatcher
TestApp0
i Thing它仅显示已直接添加到舞台的元素。
如何检测到应用程序阶段添加的所有元素?这种比较会影响应用程序性能,这意味着可能是其他方法?
为什么在事实之后添加它们?创建一个扩展BorderContainer
的新类。
public class BorderContainerWithLabel extends BorderContainer {
public var label:Label;
public function BorderContainerWithLabel() {
super();
}
override protected function createChildren():void {
super.createChildren();
// create the label here. Might have to use addChild() instead of addElement()
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplatList(unscaledWidth, unscaledHeight);
// set positioning and sizing of the label here
}
}
您可以尝试。在这里,而不是舞台上的聆听事件使用FlexGlobals.topLevelApplication
实例,我们使用 ElementExistenceEvent.ELEMENT_ADD
事件,它也提供元素,例如event.ement。我们可以轻松地做。
它也存在性能问题,但它基于您的项目。如果不再更好,则需要删除侦听器。添加侦听器事件时确切需要删除侦听器。
private function preInit():void{
myBC.addEventListener(ElementExistenceEvent.ELEMENT_ADD,onElementAdded);
}
protected function onElementAdded(event:ElementExistenceEvent):void
{
//For the as it will return null if it is not of the type you want:
var bc:BorderContainer = event.element as BorderContainer;
if(bc){
var label:Label = new Label();
label.text = "This is BorderContainer";
label.x = 10;
label.y = 10;
BorderContainer(event.element).addElement(label);
}
else{
//other than BorderContainer no prototype chain check with is operator.
}
}
在MXML中,创建自定义组件名称为BorderContainerWithlabel,然后将您的BorderContainer添加到BorderContainerWithlabel中,而不是直接添加到ApplicationContainer中。因此,我们的MYBC容器会积极收听您的添加活动。这样您就可以提高性能。
<components:BorderContainerWithLabel id="myBC"/>
myBC.addElement(yourBC);
borderContainerWithlabel.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:BorderContainer 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:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:layout>
<s:VerticalLayout/>
</s:layout>
</s:BorderContainer>