PeterWong
PeterWong

Reputation: 16011

why need to remove creation complete listener in its handler?

I found the following code snippet from this open source project Loading Spinner

public function Spinner() {
    super();
    addEventListener(FlexEvent.CREATION_COMPLETE, handleCreationComplete);
}


private function handleCreationComplete(e:FlexEvent):void {
    removeEventListener(FlexEvent.CREATION_COMPLETE, handleCreationComplete);
    if (autoPlay) {
        play();
    }
}

why the line of removeEventListener is needed? Do that mean a creationComplete event will be fired more than 1 time?

Upvotes: 1

Views: 211

Answers (1)

RIAstar
RIAstar

Reputation: 11912

The only reason for removing the listener is this:
As long as an event listener is attached to an instance of a class, that listener can never be "garbage collected" until it is removed from the dispatcher, or until the dispatcher is also eligible for garbage collection. i.e. it will keep existing in memory as long as the application runs, even if you remove it from the stage and you explicitly set it to null.
That's why it's good practice to always clean up event listeners when they are no longer needed. You may avoid memory leaks.

Upvotes: 2

Related Questions