简体   繁体   中英

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. When i do it dynamically it seems like Flash tries to find an object named "LB.anim.clock.lbclock" not 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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