Structure
Structure

Reputation: 842

Reason to use a stage instance rather than calling 'stage'?

Afraid that I may be over-thinking this and also do not know which keywords I should be using to find more information. Needless to say my searches are proving futile. I would like to know if there is a reason that, within an AS3 class, I would want to do something like this:

var myStageInstance:Stage;

//within an arbitrary class
var myStageInstance:Stage = stage;
myStageInstance.addEventListener(MouseEvent, someFunction);

as opposed to something that I would normally do:

//within an arbitrary class
stage.addEventListener(MouseEvent, someFunction);

There is no particular problem that I am looking to solve right now. I would just like to know if there is a reason to use one method over the other.

Upvotes: 0

Views: 102

Answers (3)

meddlingwithfire
meddlingwithfire

Reputation: 1437

Yes, there are reasons to maintain a reference to the stage. One example is if you are adding event listeners to the stage and need to be sure they are cleaned up in the future or want direct control over when the events come in. Here's an example:

public class Demo
{
    private var _stage:Stage;

    public function Demo()
    {
        super();
        addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
    }

    public function destroy():void
    {
        if (_stage)
        {
            _stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
            _stage.removeEventListener(Event.MOUSE_LEAVE, onMouseLeave);
            _stage = null;
        }
    }

    private function onAddedToStage(event:Event):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
        _stage = stage;

        _stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, false, 0, true);
        _stage.addEventListener(Event.MOUSE_LEAVE, onMouseLeave, false, 0, true);
    }

    private function onMouseMove(event:MouseEvent):void
    { /* Do something */ }

    private function onMouseLeave(event:Event):void
    { /* Do something */ }
}

Upvotes: 2

The_asMan
The_asMan

Reputation: 6402

the follow code will not work it is broken as myStageInstance is null until you assign it something.

var myStageInstance:Stage;
//within an arbitrary class
myStageInstance.addEventListener(MouseEvent, someFunction);

//You need to do 
var myStageInstance:Stage = stage;
myStageInstance.addEventListener(MouseEvent, someFunction);

//this is more preferred as it is a lot less code. 
stage.addEventListener(MouseEvent, someFunction);

Upvotes: 2

Jonatan Hedborg
Jonatan Hedborg

Reputation: 4432

Your code should not work, since you are not setting your stageInstance to anything.

I can't see a reason why you would ever use anything other than stage to refer to the stage instance provided, since it is practically a non-global singleton.

Upvotes: 0

Related Questions