简体   繁体   English

通过变量迭代动态访问AS3实例

[英]Access a AS3 instance dynamically by iterating with variables

I want to be able to access a instance on the stage dynamically by looping through an array containing Strings that describes the path. 我希望能够通过循环访问包含描述路径的字符串的数组来动态访问舞台上的实例。

private var clockKeeper:Array = new Array("LB.anim.clock.lbclock");

trace(stage.LB.anim.clock.lbclock.text);
for (var key in clockKeeper) {
    trace(stage[clockKeeper[key]].text);
}

When i access it manually with the first trace statement, it works. 当我使用第一个trace语句手动访问它时,它可以工作。 When i do it dynamically it seems like Flash tries to find an object named "LB.anim.clock.lbclock" not LB.anim.... 当我动态地执行此操作时,Flash似乎试图找到一个名为“ LB.anim.clock.lbclock”的对象,而不是LB.anim ....

How can i change this behaviour and make it work? 我该如何改变这种行为并使它起作用?

You should try splitting the "path" which should then consist of locally available names, and address each object in order. 您应该尝试分割“路径”,然后由本地可用名称组成,并按顺序寻址每个对象。 "Locally available names" means there should be stage.LB , and that object should have a property anim , etc etc. “本地可用名称”表示应该有stage.LB ,并且该对象应具有属性anim等。

function getObjectByPath(theRoot:DisplayObjectContainer,
    thePath:String,separator:String='.'):DisplayObject 
{
    var current:DisplayObjectContainer=theRoot;
    var splitPath:Array=thePath.split(separator);
    while (splitPath.length>0) {
        var named:DisplayObject = current.getChildByName(splitPath[0]);
        var addressed:DisplayObject=current[splitPath[0]];
        // either named or addressed should resolve! Otherwise panic
        if (!addressed) addressed=named; else named=addressed;
        if (!named) return null; // not found at some position
        splitPath.shift();
        if (splitPath.length==0) return named; // found, and last
        current=named as DisplayObjectContainer;
        if (!current) return null; // not a container in the middle of the list
    }
    // should never reach here, but if anything, just let em
    return current;
}

This provides two ways of resolving the path, by name or by property name, and property name takes precedence. 这提供了两种通过名称或属性名称解析路径的方法,并且属性名称优先。 You should then typecast the result to proper type. 然后,您应该将结果键入正确的类型。

Yes, call this as follows: 是的,请按以下方式调用:

trace((getObjectByPath(stage,clockKeeper[key]) as TextField).text);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM