pizza0502
pizza0502

Reputation: 333

Can detect the addEventListener and then remove it?

I wanna do this:

if (rightBtn.addEventListener(MouseEvent.CLICK,goRight4))
{
rightBtn.removeEventListener(MouseEvent.CLICK,goRight4);
trace("YES")
}
else{trace("NO")}

above is the code i write to a Button.

I've added the eventListener but the result still trace NO.

Any idea or proper way to do this?

And what if the rightBtn have multiple event like MOUSE_OVER, MOUSE_OUT? can i remove them all with just 1 command?

rightBtn.addEventListener(MouseEvent.CLICK,goRight4)
rightBtn.addEventListener(MouseEvent.MOUSE_OVER,goRightOver)
rightBtn.addEventListener(MouseEvent.MOUSE_OUT,goRightOut)

if (rightBtn.addEventListener(MouseEvent.CLICK,goRight4))
{
rightBtn.removeEventListener(MouseEvent.CLICK,goRight4);
rightBtn.removeEventListener(MouseEvent.MOUSE_OVER,goRightOver);
rightBtn.removeEventListener(MouseEvent.MOUSE_OUT,goRightOut);
trace("YES")
}
else{
trace("NO")
}

Upvotes: 1

Views: 6030

Answers (2)

puggsoy
puggsoy

Reputation: 1280

You can check if an object has an event listener added to it with hasEventListener(), like this:

if(rightBtn.hasEventListener(MouseEvent.CLICK))
{
    rightBtn.removeEventListener(MouseEvent.CLICK, goRight4);
    trace("YES");
}
else
{
    trace("NO");
}

You'll notice the the hasEventListener function only has one parameter, the event. This is OK in most cases though, since you probably won't have multiple listener functions for one event.

Upvotes: 4

Florent
Florent

Reputation: 12420

Your code is wrong. According to the AS3 language reference, addEventListener() returns void. You have to use hasEventListener() if you want to check if a listener was attached to your instance.

if (rightBtn.hasEventListener(MouseEvent.CLICK)) {
    rightBtn.removeEventListener(MouseEvent.CLICK, goRight4);
    trace("YES");
} else {
    trace("NO");
}

But the best way to remove the event listeners is to remove it without knowing if it had been attached to your instance!

// Will not throw any error even if no listener was attached.
rightBtn.removeEventListener(MouseEvent.CLICK, goRight4);

Upvotes: 4

Related Questions