views:

5762

answers:

4

I keep getting compiler errors when I try to access flashVars in an AS3 class.

Here's a stripped version of the code:

package myPackage {
 import flash.display.Loader;
 import flash.display.LoaderInfo;
 import flash.display.Sprite;
  public class myClass {
 public function CTrafficHandler() {
  var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myFvar;}}}

And I get a compilation error:

1119: Access of possibly undefined property root through a reference with static type source:myClass.

When I change the class row to

public class myClass extends Sprite {

I don't get a compiler error, but I do get this in the output window:

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

Via the debugger (as suggested) I can see that this.root is null.

How can I solve this problem?

A: 

I think you should extend from Sprite, but be sure to initialize it first and maybe put to the stage. Try to enable debugging and see what exactly is null as exception report says.

Michael Pliskin
+1  A: 

I found what the problem was. The class in question wasn't the main class used in the project, but rather a secondary class.

I've moved the code to the main class to get the parameters and after I got them, I sent them to the class constructor function.

Eliram
+1  A: 

As an alternative, you could try using the mx.core.Application.application.parameters object.

From the LiveDocs page for mx.core.Application:

application : Object
[static] [read-only] A reference to the top-level application.

parameters : Object
[read-only] The parameters property returns an Object containing name-value pairs representing the parameters provided to this Application.

There are two sources of parameters: the query string of the Application's URL, and the value of the FlashVars HTML parameter (this affects only the main Application).

David Crow
Note that due to the Application class being part of the mx,* packages, this only works if you're using Flex.
hasseg
Right, I should have mentioned it. Thanks for pointing that out. :)
David Crow
+1  A: 

The problem was indeed that you were attempting to access this information from a non-display object, or from outside of the document class. If you wish to access root or stage, the object that wishes to access such must be first added to the display list.

I often use flashvars for variables that are used often throughout the project. Variables like country, and language. I find that in this case it is best to catch these parameters in the document class and create public variables with said parameters as values. This will give _global style access to these variables. That all being said, you really should use global variables sparingly, especially when working on collaborative projects.

Brian Hodge