views:

206

answers:

2

Say I have the following custom component:

<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
         xmlns:s="library://ns.adobe.com/flex/spark" 
         xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
    <![CDATA[
        [Bindable]
        public var prop:String;

        private function formatProp() : String {
            return "Hello, " + prop;
        }

    ]]>
    </fx:Script>

    <s:Label text="User: {prop}"/>
    <s:Label text="Greeting: {formatProp()}"/>
</s:Group>

If I add it to my application like this:

<local:MyComponent prop="Hello"/>

The result looks like:

User: Mark
Greeting: Hello, null

It seems Flex is setting prop on my custom component after it has already initialized the child labels, so it's reliant on the property changed event to set the user label.

Is there an elegant way to make Flex wait for all of my component's properties to be set before initially evaluating bindings?

Note: I realize the formatProp function is trivial and could be included inline, but this is just a simplified example.

A: 

it is not related to component livecycle, more to binding rules. Your function "formatProp" should recieve the parameter "prop" as a parameter in order to be called when the prop is changed. Try this code:

        private function formatProp(props:String) : String {
            return "Hello, " + props;
        }
        <s:Label text="Greeting: {formatProp(prop)}"/>
Cornel Creanga
+1  A: 

The "elegant way" would be to actually provide data binding, so that you can change your property also afterwards. Your initial idea looked good, working with the answer provided by Cornel. I just wanted to mention this as your actual question sounded more like that you know your data binding is not working and you just wanted to postpone the initial setting of the variable.

Btw, should you plan to create custom components in Actionscript (instead of mxml) you'll face the opposite problem: properties are set before you had a chance to actually create your children, so you may need to buffer them if they actually should influence some childs properties.

Zefiro