views:

35

answers:

2

Is there a way to make a display object always be at the top of the display list?

For example, I know you can set the childIndex, i.e:

setChildIndex(myDisplayObject, numChildren-1);

But is there a way that an object has sensed that something else has been added to the display list and restack themselves accordingly?

+2  A: 

You can override the addChild() method in the parent object. In that method you can move your child to the top using

setChildIndex(myDisplayObject, numChildren-1);

In this way everytime an object is added to the parent, the parent moves your object to the top.

wezzy
That code was already in my question!
redconservatory
it's not exactly, my idea is to override addChild() of your container and in just one line of code you can get what you want. I know that you already wrote that line of code, but the keypoint is the place where you put that line :)
wezzy
+4  A: 

You can listen to the Event.ADDED event on the container. This event will bubble up, so you'll get called whenever a display object is added to the container or any of its children.

Here's an example of how you could do this. You'll see the black box always stays on top.

var container:DisplayObjectContainer = this; // this is a frame script but just change this line as necessary
container.addEventListener(Event.ADDED,handleAdded,true);

function handleAdded(e:Event):void {
    // this if tries to cover some edge cases, unlikely to happen in your code, from your description
    if(container == topElement.parent && container.numChildren > 0 && container.getChildIndex(topElement) != container.numChildren - 1) {
        container.setChildIndex(topElement,numChildren - 1);
    }
}

function getSprite(c:uint):Sprite {
    var sp:Sprite = new Sprite();
    sp.graphics.beginFill(c);
    sp.graphics.drawRect(0,0,100,100);
    sp.graphics.endFill();
    return sp;
}

var topElement:Sprite = getSprite(0);

container.addChild(topElement);
var sp:Sprite = getSprite(0xff0000);
container.addChild(sp);
sp.addChild(getSprite(0xff00));
var sp2:Sprite = getSprite(0xff);
container.addChild(sp2);

However, I think it's much simpler and cleaner just to have 2 containers, say, top and bottom, kind of like layers. In top you'd add the element that always must be on top (or this could be your element as you probably don't need to have this extra container). In bottom you'd add and remove whatever you want. Then you can forget about manually restacking stuff (at least to keep the top element atop).

Juan Pablo Califano
This is great, thanks.
redconservatory