user1713984
user1713984

Reputation: 13

Removing event listeners in for loop

I'm fairly new to Actionscript 3 and I have a question to ask. I'm doing a fairly simple spot the difference game and I am adding event listeners to the clickable differences in a for loop. My goal is that after I click the difference it also removes its event listener.

Here's my code:

function addDifferences()
{
    for (var i = 1; i < 4; i++)
    {
        var difference = level1_left["level1_left_diff" + i];
        difference.alpha = 0;
        difference.addEventListener(MouseEvent.CLICK, onDifferenceClick);

        function onDifferenceClick(evt:Event):void
        {
            evt.currentTarget.alpha = 1;
            evt.currentTarget.play();
            found++;
            evt.currentTarget.removeEventListener(MouseEvent.CLICK, onDifferenceClick);
        }
    }
}

The problem is I can only access the last element (difference) in the for loop, so I can only remove the last eventlistener. I want to be able to remove eventlisteners for every element.

Can you please help me with this? Thanks!

Upvotes: 1

Views: 544

Answers (2)

catholicon
catholicon

Reputation: 1165

You don't really need to have all the items pushed into an array. All you need to do is to pass correct function to removeEventListener. In you code, every call to removeEventListener is getting the last allocated inline function. Just create a non-inline function like:

function addDifferences()
{
    for (var i = 1; i < 4; i++)
    {
        var difference = level1_left["level1_left_diff" + i];
        difference.alpha = 0;
        difference.addEventListener(MouseEvent.CLICK, onDifferenceClick);
    }
}

function onDifferenceClick(evt:Event):void
{
    evt.currentTarget.alpha = 1;
    evt.currentTarget.play();
    found++; //assuming this is a global variable accessible from this function!!!
    evt.currentTarget.removeEventListener(MouseEvent.CLICK, onDifferenceClick);
}

Upvotes: 0

blue112
blue112

Reputation: 56412

You should store your elements in an array, which can be looped on later.

var differences:Array = new Array(); //Class variable, or global if you don't use classes

function addDifferences()
{
    for (var i = 1; i < 4; i++)
    {
        var difference = level1_left["level1_left_diff" + i];
        difference.alpha = 0;
        difference.addEventListener(MouseEvent.CLICK, onDifferenceClick);

        differences.push(difference);
    }
}

//Don't create this function four time
function onDifferenceClick(evt:Event):void
{
    evt.currentTarget.alpha = 1;
    evt.currentTarget.play();
    found++;

    for (var i = 0; i < differences.length; i++)
    {
        differences[i].removeEventListener(MouseEvent.CLICK, onDifferenceClick);
    }

    //You can empty array afterwars, if you wish to start a new round (with addDifferences)
    differences = new Array();
}

Upvotes: 1

Related Questions