Richard
Richard

Reputation: 125

Do I have to set a removeEventListener when I called addEventListener?

I'm a beginner of ActionScript 3. Recently I'm trying to use addEventListener to invoke function. I found that there are some examples add a removeEventListener when they invoke functions, such as:

public function Away3DMultiMarkerDemo()
    {
        addEventListener(Event.INIT, initIN2AR);
        super();
    }

    private function initIN2AR(e:Event = null):void
    {
        removeEventListener(Event.INIT, initIN2AR);

        in2arLib.init( workW, workH, maxPoints, maxReferences, 100, stage );
        in2arLib.setupIndexing(12, 10, true);
        in2arLib.setUseLSHDictionary(true);

        in2arLib.addReferenceObject( ByteArray( new DefinitionaData0 ) );
        in2arLib.addReferenceObject( ByteArray( new DefinitionaData1 ) );

        in2arLib.setMaxReferencesPerFrame(2);

        in2arLib.setMatchThreshold(40);

        intrinsic = in2arLib.getIntrinsicParams();

        initCamera();
        initAway3D();
        initText();
        initListeners();
    }

My question is that do I need to set a removeEventListener each time when I called addEventListener? I did some research that the purpose of adding the removeEventListener is to release memory, otherwise program will keep listen events.

Upvotes: 2

Views: 229

Answers (2)

Adam Harte
Adam Harte

Reputation: 10520

It is good practice to remove your listeners when you no longer need them. But that is a call you must make in each situation.

Adding an event listener by default will hang onto a reference of the thing it is added to. So if you add a listener to a movieclip, and delete that movieclip, it will not be garbage collected because the event listener still has a reference to it. For this reason it is good to remove any listeners on an object as part of your deletion process. Of course you can also use the "weak reference" argument in the addEventListener method, so the listener will not keep the garbage collector from destroying the object.

In the case of the Event.INIT event in your example; That should only ever fire once, so the event handler is the perfect place to make sure you remove the listener.

Upvotes: 3

tckmn
tckmn

Reputation: 59323

No. You only have to do this if you want the event to execute only once. You also call it when you no longer need the listener, so that it doesn't waste memory.

If you call it as the very first statement in the function that is called when the event is fired, it will ensure that the listener is only called once.

Upvotes: 0

Related Questions