开发者

MXML-class initialization order

I have written a few custom components in Flex 4, and run into this issue a few times.

var myForm:MyForm = new MyForm;
myForm.SetData(data);
addElement(myForm);

Now Imagine I am calling these functions from a non-constructor function of a Panel or VGroup (or any other container). Annoyingly, during MyForm.SetData(), not all fields of myForm that are declared there are yet initialized. Such as:

<s:VGroup id="dataGroup">

If my SetData()-function wants to access dataGroup (for the reason to .addElement() the just recieved data to it), it just fails with a nullpointer exception, because dataGroup is not yet created, despite this being after the constructor. How can guarantee that the form开发者_Go百科 was initialized fully?


Listening for the creationComplete event and adding your components in the handler for the event is one way to do this. This is what Sam DeHaan suggested.

Another way you can do this is to override the createChildren() function. This is the function that creates and adds all of a component's child components. Code would look something like this:

override public function createChildren():void
{
    super.createChildren();

    var myForm:MyForm = new MyForm;
    // Note that data may be null here, best to 
    // override commitProperties() to set it.
    myForm.SetData(data);   
    addElement(myForm);
}

The docs on the component lifecycle will provide a ton of detail on this topic.


Unless I'm misunderstanding your question,

You should put the code that runs into this null pointer exception in a creationComplete callback on the container that you need defined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜