Reputation: 172
I have a pure AS3 project (no mxml).
When compile using flex SDK 4.6, a class (and its static variables) is inited at the very first time when it is referenced (when static member being used or class instance being created).
When compile using air SDK 24.0, many class (and its static variables) are inited right at application start, not right before they are referenced. Why? Is there any compile option or SWF meta tag to prevent this?
My static variables need some other data to init, those data are dynamic loaded at run time, not immediately available at application start. So, i do not want them to be inited so early.
Upvotes: 0
Views: 352
Reputation: 52173
My static variables need some other data to init, those data are dynamic loaded at run time, not immediately available at application start. So, i do not want them to be inited so early.
Doing this is dangerous to begin with, even if it worked in ASC 1.0. If you need to load data before computing some derived values, you shouldn't rely on static initialization.
You could use a singleton, or just use a static initialize()
method which you explicitly call after the data is loaded:
private function handleDataLoaded(e:DataEvent):void {
MyStaticStuff.initialize(e.data);
}
Or, as a drop-in replacement, you can refactor your static variables to getters which internally call an init function:
public class MyStaticStuff {
// before
public static const SOME_VALUE:Number = LoadedData.data.something;
// after
private var initialized:Boolean = false;
private static _SOME_VALUE:Number;
public static function get SOME_VALUE():Number {
initialize();
return _SOME_VALUE:Number;
}
private static function initialize():void {
if (!initialized) {
initialized = true;
_SOME_VALUE = LoadedData.data.something;
}
}
}
In this case places that use MyStaticStuff.SOME_VALUE
don't have to be changed, and the values will be initialized the first time they are referenced like you had before. But it would probably be a better pattern to refactor your code to use a singleton and/or explicit initialization.
Upvotes: 2