Jan
Jan

Reputation: 43169

AS3 delete object when clicked

I want to set an object to null when it's being clicked and I'm trying to implement this code:

        public function onClick(evt:MouseEvent):void{
        var thisPatient = evt.target;
        thisPatient = null;
    }

However, the element is still on the stage.

Upvotes: 1

Views: 2754

Answers (4)

bitmapdata.com
bitmapdata.com

Reputation: 9600

In my experience, Register for a events object, you must remove all of the events. all events will be removed completely manually. removeChild on the object that will not release all of the events. the removeChild but, finely memory leak occurs. This is because you did not remove the event. Before you remove an object, you must remove the event.

Upvotes: 0

eleven
eleven

Reputation: 6847

public function onClick(evt:MouseEvent):void{
    var thisPatient = evt.target;
    (thisPatient as DisplayObject).parent.removeChild(thisPatient);
    //or if thisPatient is this
    parent.removeChild(this);
}

But it's bad practive to allow children to remove itself. More right solution is dispathing event because parent must decide remove or not remove child.

public function onClick(evt:MouseEvent):void{
    dispatchEvent(new Event("removeMe", true));
}

//parent's code...
child.addEventListener("removeMe", removeHandler);

Upvotes: 3

user1350184
user1350184

Reputation:

You just have to do removeChild(thisPatient) and if you put the object inside another object you have to do parent.removeChild(thisPatient)!

Upvotes: 2

AlBirdie
AlBirdie

Reputation: 2071

Setting it to null doesn't suffice. You also have to remove it from its parent container using removeElement() or removeChild() depending on what kind of container you're using.

Upvotes: 2

Related Questions