Is there a way to check if DisplayObject A is a descendant of DisplayObject B?

北城余情 提交于 2019-12-24 09:30:49

问题


I would like to be able to quickly check if a given DisplayObject is a descendant (not in the inheritance sense - ie. child, grandchild, great-grandchild, great-great-grandchild, etc.) of another DisplayObject.

There doesn't seem to be a native way to do this and I can only think of two ways to achieve it:

  1. Create the mother of all nested loops. Seems a bit, I dunno, wrong?
  2. Dispatch a bubbling event at the 'child' and check if the potential 'parent' receives it.

Am trying the latter now, but would appreciate some input. I'd like to create a nice utility static function, eg:

static public function isDescendantOf(child:DisplayObject, parent:DisplayObjectContainer):Boolean { 

    var isDescendant: Boolean = false;

    // perform some magical 
    // check that returns true 
    // if it is a descendant

    return isDescendant;
}

回答1:


Holy horned moose, event for that...

parent.contains(child);

See reference for DisplayObjectContainer.contains().




回答2:


Ok I got it working, but it uses a nasty anonymous function.

Wonder if it can be improved?

static public function isDescendantOf(child:DisplayObject, parent:DisplayObjectContainer):Boolean {
    const HELLO:String = "hello";
    var isDescendant:Boolean = false;

    parent.addEventListener(HELLO, function(e:Event):void {
       isDescendant = true;
    });

    child.dispatchEvent(new Event(HELLO, true, false));
    return isDescendant;
}


来源:https://stackoverflow.com/questions/4022966/is-there-a-way-to-check-if-displayobject-a-is-a-descendant-of-displayobject-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!