AS3:查找指定类型的父级

时间:2014-02-03 18:45:48

标签: actionscript-3

我的代码中有这种重复的模式:

var scroller:Object = target;
while(scroller != null && !(scroller is Scroller) ) {
    if(scroller.hasOwnProperty('parent')) {
        scroller = scroller.parent;
    } else return;
}

我想要的是像这样调用泛型函数:

var scroller: Scroller = Scroller(dotParent(target, Class(Scroller)));

但我是语言的新手(我来自C#),所以我不知道该用什么比较。我需要它来处理任何类型,而不仅仅是滚动器。

1 个答案:

答案 0 :(得分:0)

以下是此类功能的示例:

protected function dotParent(target:DisplayObject, parentClass:Class):DisplayObject
{
    var res:DisplayObject = target;
    while(res && !(res is parentClass)) 
    {
        if(res.parent) 
        {
            res = res.parent;
        } 
        else
        { 
            return null;
        }
    }
    return res;
}

测试:

    //create test display list: stage->movieclip->sprite
    var sp:DisplayObject = (addChild(new MovieClip()) as MovieClip).addChild(new Sprite());

    var st: Stage = dotParent(sp, Stage) as Stage;
    trace(st);
    var mc: MovieClip = dotParent(sp, MovieClip) as MovieClip;
    trace(mc);
    var sh: Shape = dotParent(sp, Shape) as Shape;
    trace(sh);

输出:

[object Stage]
[object MovieClip]
null