Level screen

I got a problem, there I have two movie clips each is linked with action script file. The first movie clip “level screen” has a loop (code is not shown there) in it’s code which addChild a lot of same icons (but each has different number) and add them to array levelArray. Then when I click a icon, for example one with nmber 31, it addChild the other movie clip “main screen” and send it a variable “levelNumber” with value 31, so mainScreen could then addChild a level 31. Below is the code for levelScreen checking what icon is being clicked and taking right actions. However first I will write how i imagined this to work step-by-step

  1. The timer activates the loop over and over again, so when it comes to end, it starts again.

  2. The loop loops through array called levelArray, in which all icons are stored.

  3. Inside the loop it first defines a variable checkIcon which is the icon at which the loop is.

  4. Now there the things get complicated, I want to add a MouseEvent listener to icon, if it would be triggered the function “onLevelButtonClick” should be executed, and the I want to remove the listener again, so I wont have 1000 listeners on same icon after some time.

  5. And the function dispatch event which add main screen and send it a variable levelNumber, which should be number of icon clicked.

public function onClickCheck(timerEvent:TimerEvent):void {
for (var a:int= 0; a< levelArray.length; a++) {
var checkIcon:MovieClip = levelArray[a];
checkIcon.addEventListener(MouseEvent.CLICK, onLevelButtonClick);
function onLevelButtonClick(mouseEvent:MouseEvent):void {
dispatchEvent( new NavigationEvent( NavigationEvent.START ) );
mainScreen.levelNumber = a
}
checkIcon.removeEventListener(MouseEvent.CLICK, onLevelButtonClick);
}
}

I think it doesnt work beacuse the code is executed in following order:

  1. checkIcon.addEventListener(MouseEvent.CLICK, onLevelButtonClick);
  2. checkIcon.removeEventListener(MouseEvent.CLICK, onLevelButtonClick);
  3. the function should be executed now, but it wont be since It already removed Event Listener…