我在我的Flex应用程序的各种自定义组件实例。 我想通过循环递归他们并得到他们的实例ID。 递归部分对我来说很重要。 谁能告诉我什么是做到这一点的最好方法是什么? 我曾尝试这样做,但它没有这样做递归:
for each (var myItem:* in this.MasterContainer.childDescriptors)
{
trace(myItem.id);
}
我在我的Flex应用程序的各种自定义组件实例。 我想通过循环递归他们并得到他们的实例ID。 递归部分对我来说很重要。 谁能告诉我什么是做到这一点的最好方法是什么? 我曾尝试这样做,但它没有这样做递归:
for each (var myItem:* in this.MasterContainer.childDescriptors)
{
trace(myItem.id);
}
这将做到这一点:
private function findControlsRecursive(current:DisplayObjectContainer, controls:ArrayCollection):void
{
for(var idx:int = 0; idx < current.numChildren; idx++)
{
var child:DisplayObject = current.getChildAt(idx);
controls.addItem(child.name);
var childContainer:DisplayObjectContainer = child as DisplayObjectContainer;
if(childContainer)
{
findControlsRecursive(childContainer, controls);
}
}
}
public function findControls():ArrayCollection
{
var controls:ArrayCollection = new ArrayCollection();
findControlsRecursive(Application.application as DisplayObjectContainer, controls);
return controls;
}
我用这个来的所有组件遍历的几种方法,有些方法建立结果在累加器acc
(例如,写入字符串,使所有的计数,等等)。 迭代包括组件镶边时useRaw
是true
。
/**
* Descends through subcomponents applying function
*/
public static function visitComponent(component:Object, fn:Function, useRaw:Boolean = false, acc:Object = null):Object {
var newAcc:Object = fn.call(null, component, acc);
if (component is mx.core.Container) {
var kids:mx.core.Container = mx.core.Container(component);
var childList:IChildList;
if (useRaw) {
childList = kids.rawChildren;
} else {
childList = kids;
}
for (var i:int = 0; i < childList.numChildren; ++i) {
visitComponent(childList.getChildAt(i), fn, useRaw, newAcc);
}
} else if (component is DisplayObjectContainer) {
var displayObjContainer:DisplayObjectContainer = component as DisplayObjectContainer;
for (var j:int = 0; j < displayObjContainer.numChildren; ++j) {
visitComponent(displayObjContainer.getChildAt(j), fn, useRaw, newAcc);
}
}
return newAcc;
}
/**
* Randomly resets backgroundColor of subcomponents
*/
public static function colorizeComponent(component:Object):void {
var fn:Function = function(c:Object, acc:Object):Object {
if (c is UIComponent) {
(c as UIComponent).setStyle("backgroundColor", Math.random() * uint.MAX_VALUE);
(c as UIComponent).setStyle("backgroundAlpha", 0.2);
}
return null;
}
visitComponent(component, fn);
}
迈克尔·布鲁尔 - 戴维斯的功能比这个例子更加通过(处理rawchildren,非Flex组件等),但有没有必要递归遍历树:
function toEveryComponentDo(f:Function):void
{
var component:UIComponent = Application.application;
var components:Array = component.getChildren();
f(component);
while (components.length > 0)
{
var childComponents:Array = [];
for each (component in components)
{
f(component);
if (component is Container)
{
childComponents = childComponents.append(Container(component).getChildren());
}
}
components = childComponents;
}
}