17 January 2014

AS3 Removing All Event Listeners

We can say that in ActionScript 3 Event Listeners have cumulative effect. Lets demonstrate this feature.
Our world-wide famous "square" object is also involved in this story.
First, we have to import some kind of event.

import flash.events.MouseEvent;

Now, that's great! We have something to work with.

square.addEventListener(MouseEvent.CLICK, onClick);

function onClick(evt:MouseEvent):void
{
    evt.target.x += 10;
    // square.addEventListener(MouseEvent.CLICK, onClick2);
}


What happened here? If you test it, code will move our square 10 pixels to the right per click. Considering coordinate axes this is expected behavior. Next, lets uncomment that confusing line and add another function definition.

function onClick2(evt:MouseEvent):void
{
    evt.target.x -= 15;
    // square.removeEventListener(MouseEvent.CLICK, onClick);
}


Now result is that first our world-wide famous pal goes 10 pixels right and than 15 pixels left, which means both functions are executed. But if we uncomment removeEventListener line our pal goes only 15 pixels to the left.

There is no built-in way to remove all event listeners at once in ActionScript 3.0. There is a way to check if specific event listener is already attached. You can do this using hasEventListener on your object. Using some kind of loop if object has specific listener you can remove it. This solution has limitations.

If you are not using AS3 Signals maybe some help you can find in this post.

*_*

0 comments:

 

template by blogger templates