Posted by: thinklunatic | June 9, 2009

StageManager in AS3

In AS3, i often get frustrated over adding Event Listeners to the stage in other classes. Often we will get the follow error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.

After reading the first few chapters in the book – Actionscript 3.0 Design Patterns. I thought of using the Singleton Pattern and created a StageManager, purpose of it was to allow any class to access the stage and add Event listeners to it easily. Well, i tried this out last night and i think i might had the solution i want, as least it works fine for me now. Now to add an Event Listener in another class, all i need to do is just simply import in the StageManager class in and call the STAGE property and add a Listener to it:

StageManager.STAGE.addEventListener(MouseEvent.CLICK, onStageClick, false, 0, true);

Yes, it that simple, however, prior to this, we will need to init the StageManager in the Base Class by just adding 2 sentence:
StageManager.getInstance();
StageManager.STAGE = this.stage;

Feel feel to download my sample and try it out & feel free to comment how you guys feel about this.

stageListener.zip

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: