views:

62

answers:

2

hello! can you tell me a simple and clean way to pass the dimension of the stage to another class, imported in my documentclass?

thanks a lot!

A: 

Any class that is added to the display list can simply use stage.stageWidth and stage.stageHeight. If the instance is not added to the display list, then you can either pass it to the instance, define a Singleton which contains the information or use a public static variable inside your DocumentClass to be used for access.

sberry2A
unfortunately i alway get a TypeError: Error #1009: Cannot access a property or method of a null object reference.
Luca
Is your imported class added to the display list at the time that error is thrown? If not, there's your problem. As sberry2A said, if you can't guarantee that your class will be added to the display list before the method that needs the stage width and height will be called, you could use a singleton that's added to the display list on startup to retrieve that info.The other option would be to wrap your code that needs to know the stage width/height inside an if (stage != null) { .. do stuff .. } block. Assuming your class doesn't need to do anything until it's on the stage, that would work.
Alterscape
Don't use a Singleton! Very bad practice (shame on you sherry2A for suggesting that!)
TandemAdam
@TandemAdam... Very bad practice... using Singletons? no.
sberry2A
@sberry2A - http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
TandemAdam
+2  A: 

Try putting these two lines in the constructor of the Class that you want to use the stage width/height:

if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);

Make sure you import the flash.events.Event class.

Then create this method inside the same Class:

private function init(e:Event = null):void 
{
    removeEventListener(Event.ADDED_TO_STAGE, init);
    trace(stage.stageWidth, stage.stageHeight);
}

This init method will be called only when your class is added to the stage. This means the stage variable will be accessible (not null).

This is just a test to show that the stage object is only available when the displayObject is added to the display list.

TandemAdam
you're the man TandemAdam!!! so simple and clear! thanks a lot!! :)
Luca