In my Flash project I have a movieclip that has 2 keyframes. Both frames contain 1 movieclip each.
frame 1 – Landing
frame 2 – Game
The flow of the application is simple:
- User arrives on landing page (frame 1)
- User clicks “start game” button
- User is brought to the game page (frame 2)
- When the game is over, the user can press a “play again” button which brings them back to step 1
Both Landing and Game movieclips are linked to separate classes that define event listeners. The problem is that when I end up back at step 1 after playing the game, the Game event listeners fire twice for their respective event. And if I go through the process a third time, the event listeners fire three times for every event. This keeps happening, so if I loop through the application flow 7 times, the event listeners fire seven times. I don’t understand why this is happening because on frame 1, the Game movieclip (and I would assume its related class instance) does not exist – but I’m clearly missing something here.
I’ve run into this problem in other projects too, and tried fixing it by first checking if the event listeners existed and only defining them if they didn’t, but I ended up with unexpected results that didn’t really solve the problem.
I need to ensure that the event listeners only fire once. Any advice & insight would be greatly appreciated, thanks!
If you have two frames with different clips on the same layer, each time that frame “enters”, that clip is created. When it “leaves” the clip is removed, but it still will be kept around and not be garbage collected. So the next time the frame enters a different clip is “created” and it gets its own listener. Your best bet is to remove the listeners when you change frames. I usually get around this kind of stuff by having a listener for
Event.REMOVED_FROM_STAGEin each class. If it’s removed, then you clean up the remaining listeners.You may also want to experiment with “weak listeners”:
The “true” makes the link “weak” so if an object is removed, the garbage collector can pick it up. I wouldn’t rely on this completely though. Better to manually remove references so you can be sure.
This answer assumes a lot of course. It’d be helpful if you posted code/screenshots/flas to better diagnose.