Making sure your Flex is initialized

Posted by – March 20, 2008

I’ve just banging my head against a brick wall for the past half an hour trying to work out why a bit of Flex MXML was crashing as soon as it was loaded. I had a situation whereby a label component was coming back as null once called from an event handler. Dipping into the debugging view confirmed this.

The issue? Well, the event was fired as soon as it’s parent component was loaded, which was also before the Label had started to load (note that the order of nodes in your MXML does make a difference). Consider the following code:

[viewcode] src=”2008/03/initialized.txt” geshi=xml[/viewcode]

By using this.initialized you are able to check that the parent node has loaded (in this case, the Application, but sometimes the containing component), and therefore run your code relatively safely.

I guess best practise would say that you should always check for initialization signatures regardless – better safe than sorry.

4 Comments on Making sure your Flex is initialized

Closed

  1. Eric Cancil says:

    Or you could choose to make things a lot more rigid and have it more like this

    private var _theText:String;
    private var theTextDirty:Boolean = false;
    public var label:Label;

    public function set theText(val:String):void{
    _theText = val;
    theTextDirty = true;
    invalidateProperties();
    }

    override protected function commitProperties():void{

    super.commitProperties();

    if(theTextDirty){
    theTextDirty = false;
    label = _theText;
    }
    }

  2. Eric Cancil says:

    oops forgot the getter

    public function get theText():String{
    return _theText;
    }

  3. Joeflash says:

    Wouldn’t it be a better idea to disable user interaction until the Application.creationComplete event has been called?

  4. Neil says:

    @Joe indeed – but it’s always better to be safe than sorry ;)