Zwiggy
Zwiggy

Reputation: 21

Actionscript 3 EventListener

I am fairly new to actionscript 3 and I would like to know how can I make EventListener to work only once. Right now it works after every click, but I need to get it work only with first click. After click it displays a ball on the stage where the click was made. I need to get to the point where only one ball appears and after that click should do nothing.

my code:

stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
function onClick(evt:MouseEvent):void {
    var ball:MovieClip = new Ball();
    ball.x = stage.mouseX;
    ball.y = stage.mouseY;
    addChildAt(ball,0);
}

Upvotes: 1

Views: 72

Answers (2)

user2655904
user2655904

Reputation:

One possible solution is to remove the EventListener.

stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
function onClick(evt:MouseEvent):void {
    stage.removeEventListener(MouseEvent.CLICK, onClick);
    var ball:MovieClip = new Ball();
    ball.x = stage.mouseX;
    ball.y = stage.mouseY;
    addChildAt(ball,0);
}

Another solution is a simple bool variable, in case you need the eventlistener for something else.

var clickedOnce:Boolean = false;
stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
function onClick(evt:MouseEvent):void {
    if(!clickedOnce){
       clickedOnce = true;
       var ball:MovieClip = new Ball();
       ball.x = stage.mouseX;
       ball.y = stage.mouseY;
       addChildAt(ball,0);
    }
}

Upvotes: 3

www0z0k
www0z0k

Reputation: 4434

You need to call removeEventListener() as follows:

stage.addEventListener(MouseEvent.CLICK, onClick,false,0,true);
function onClick(evt:MouseEvent):void {
    stage.removeEventListener(MouseEvent.CLICK, onClick);
    var ball:MovieClip = new Ball();
    ball.x = stage.mouseX;
    ball.y = stage.mouseY;
    addChildAt(ball,0);
}

Upvotes: 3

Related Questions