Flex Instantiated Object - wait for creationComplete
I have a simple component I created which I instantiate in my main progra开发者_JAVA技巧m like so:
newMessage = new MessageDetail();
newMessage.body.text = "Hello World";
I receive the error "Cannot access a property or method of a null object reference" on the second line because newMessage was not fully created prior to hitting the second line of code trying to set my "body" textarea's text. I know I can build a "creationComplete" event handler, but isn't there a simpler way to do this?
Don't access sub-components at all.
Instead make regular old properties on your component. Have the component bind those values to visual components.
For example:
MyComponent.MXML:
<mxml blah blah blah>
<script>
[Bindable] public var bodyText;
</scipt>
<mx:TextArea text="{bodyText}" />
</mxml>
In your code:
myComponent = new MyComponent()
myComponent.bodyText = "Hello World!";
In general, I believe sub-components being public by default was a huge mistake in Flex.
I can recommend to create create all children in your component by overriding method createChildren(). It will make sure all children are instantiated. More here and here
public class MessageDetail()
{
// ...
private var body:TextArea;
// ...
protected override function createChildren():void
{
super.createChildren();
body = new TextArea();
addChild(body);
}
EDIT:
newMessage = new MessageDetail();
addChild(newMessage); // During this step all children will to be initialized
newMessage.body.text = "Hello World";
Thanks to Michael Brewer-Davis for comment
精彩评论