Click a display object to remove it

Hey all,

I would like to add some sort of event listener to an object upon its addition to the display list, such that clicking on the object removes it. How do I do that?

It would look something like this, although this doesn’t work…


var foo = new CustomObject();
addChild(foo);
foo.addEventListener(MouseEvent.CLICK, removeFoo);
 
function removeFoo(event:MouseEvent):void {
     removeChild(event.target);
}

The part that wouldn’t work of course is “removeChild(event.target)”. I guess I could do something like this:


function removeFoo(event:MouseEvent):void {
     if (foo) {
          if (foo.parent != null) {
               removeChild(foo);
          }
     }
{

…but I’m hoping for something a bit more modular than that.

Any help?

Thanks,

Try this…

Document Class: http://www.privatepaste.com/e4r6wyufj4

FooObject Class: http://www.privatepaste.com/0fvUBkevhE


myObject.addEventListener(MouseEvent.CLICK, removeObject);

function removeObject(e:MouseEvent):void
{
     e.target.parent.removeChild(e.target);
}

Fastest way (one listener) with drawback

container.addEventListener(MouseEvent.CLICK, removeObject);
function removeObject(event:MouseEvent):void{
     container.removeChild(event.target);
}

All in container will be removed;
Errors can occur when mouseChildren is true.

note that event.target is the lowest most display object in the heirarchy of the object clicked. If you want the “target” object, in that the object you originally assigned the listener to, use event.currentTarget.

In either case, to be sure you’re removing the object from the right parent, you would want to use
target.parent.removeChild(target);