在AS3中按类名获取实例

时间:2011-09-17 10:32:55

标签: actionscript-3 flash-cs5

我需要根据特定的类名获取我的舞台中的所有实例。我这样做:

var class_ref:Class = getDefinitionByName('fran.MyOwnClass') as Class;
var element;

for (var i:uint = 0; i < this.parent.numChildren; i++)
{
    element = this.parent.getChildAt(i);
    if (element is class_ref)
    {
        trace('Found element of class fran.MyOwnClass');
    }
}

但我想要一种更好的方式(更有效率,而无需检查所有MC)。有可能吗?

2 个答案:

答案 0 :(得分:1)

如果您可以从应用程序生命的最初阶段开始跟踪实例,我建议您只需添加事件监听器:

// in document class constructor, before doing anything else
stage.addEventListener(Event.ADDED, stage_addedHandler);
stage.addEventListener(Event.REMOVED, stage_removedHandler);

private function stage_addedHandler(event:Event):void
{
    var obj:DisplayObject = event.target as DisplayObject;
    // do something, e.g. if (obj is MyClass) objCounter++;
}
...

如果您无法从头开始跟踪,则无法避免循环。只需使它们更加优化:

var n:int = container.numChildren;
while (n-- > 0)
{
    ...
}

覆盖addChild()和其他地方 - 这在实际项目中根本不可能解决。

答案 1 :(得分:0)

您可以通过扩展容器类并覆盖其addChild()addChildAt()removeChild()removeChildAt()函数来保留某个类型的所有MC的列表。< / p>

public class MySprite extends Sprite {

    public var ownClasses:Vector.<MyOwnClass> = new Vector.<MyOwnClass>();

    override public function addChild(child:DisplayObject):DisplayObject {
        addOwnClass(child as MyOwnClass);
        return super.addChild(child);
    }

    override public function addChildAt(child:DisplayObject, index:int):DisplayObject {
        addOwnClass(child as MyOwnClass);
        return super.addChildAt(child, index);
    }

    private function addOwnClass(child:MyOwnClass):void {
        if (child) ownClasses.push(child);
    }

    override public function removeChild(child:DisplayObject):DisplayObject {
        removeOwnClass(child as MyOwnClass);
        return super.removeChild(child);
    }

    override public function removeChildAt(index:int):DisplayObject {
        removeOwnClass(getChildAt(index) as MyOwnClass);
        return super.removeChildAt(index);
    }

    private function removeOwnClass(child:MyOwnClass):void {
        if (child) {
            var i:int = ownClasses.indexOf(child);
            if (i != -1) ownClasses.splice(i, 1);
        }
    }

}

使用此类,每次添加子项时,都会检查它是否为MyOwnClass,如果是,则将其添加到ownClasses列表中。类似于删除孩子。

现在,您可以在需要时轻松访问列表,而无需循环播放MC。

public class Main extends MySprite
{
    public function Main()
    {
        addChild(new Sprite());
        addChild(new MyOwnClass());
        trace(ownClasses);
    }
}

这将输出[object MyOwnClass]