views:

669

answers:

2

I have a simple component I created which I instantiate in my main program 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?

A: 

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

zdmytriv
This is true but not relevant--the createChildren() method is fine here. But it isn't called until initialize(), i.e., when the object is added to the display list.
Michael Brewer-Davis
So using this method theres no way I can really use the design view to see what its going to look like? My MessageDetail component has about 8 child components. It would be nice if there was a wait function to wait for a specified object to load.
Chris Klepeis
My point was that the code in your edit, using addChild(), would have worked even without a custom createChildren() method.
Michael Brewer-Davis
+2  A: 

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.

Marc Hughes