Workings of DisplayObjectContainer.contains()?

I often find myself writing code like this :

if (child_sprite != null && parent_sprite.contains(child_sprite)) parent_sprite.removeChild(child_sprite);

I wonder if there’s a reason why contains() doesn’t do the null check itself ? :thinking:

I think that’s a good idea

However, on the Flash target, it throws an error:

An ActionScript error has occurred:
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/contains()

We could make it return false on other platforms, but you would still need it for Flash :slight_smile:

Sorry, I’m not a 100% sure I understand why that is … :confused:
With my limited programming experience, it seems like this should work (but it doesn’t on Flash) :

       public function contains (child:DisplayObject):Bool {
		
            if ( child == null) return false; //why does this not work ?

		while (child != this && child != null) {
			child = child.parent;
		}
		return child == this;
	}

Maybe

if(child_sprite!=null&&child_sprite.parent!=null)
{
    child_sprite.parent.removeChild(child_sprite);
}

When we compile to Flash, we use the “openfl/externs/core” and “openfl/externs/extras” files. When you import openfl.display.DisplayObject, on Flash it is a link to “flash/display/DisplayObject.hx”, which really tells Haxe that Flash Player has a built-in DisplayObject type that we want to use.

We do not control the behavior of displayObject.contains on Flash Player, instead we work out the wiring so that it calls the code that Adobe has written inside of the ActionScript Virtual Machine.

Your code sample would work on all targets… except for Flash, since “openfl/display/DisplayObject.hx” is used for all other platforms :slight_smile:

@singmajesty : Thank you so very much for taking the time to explain all these things to us ! :hugs:

1 Like