My friends and family are under attack in Ukraine. Donate to protect them directly or help international organizations.

AS3 data binding and component states

February 28th, 2008

If you ever developed a complex data-driven application, you probably stumbled upon the data binding nightmare. Altough a great feature in Flex (a central one in my opinion), it lacks a bit of control.

I needed a form with multiple states depending on the flavor of the edited object. This way, I could have common fields to all object types and add a couple of fields based on the object type. However, these fields' values were bound to properties of the edited object. When selecting an object from the list, the fields should update themselves. Bindings are executed to set field values. Now, since I use form states, all fields are technically on the stage and all bindings will execute, regardless of the type of the selected object.

Basic example

I have a form to edit animal properties (number of legs, head size, etc.)

I have some extra fields depending on the animal type (mammals have fur length and density, birds have wing span, etc.)

Every animal type has an associated state:


    
        
    
    
        
            
                
                    
                
            
        
    

The animal variable is set when an element is selected from a list. It can be an instance of a custom class Mammal or Bird which extends the Animal class. The state also changes according to the type selected. The problem occurs when I select a non-Mammal. The binding will execute, expecting a Mammal for the TextInput's text property. An error will be thrown saying that Bird (or other) could not convert to Mammal. This is to be expected, as the TextInput in question remains on the stage even if the state is invisible.

What's the solution? Perhaps not the most neat, but it works: create extra variables for every type. Now you will have animal:Animal, mammal:Mammal and bird:Bird variables with their respective types. When an animal is selected, every type except the needed one is set to null. The animal variable still points to the selected animal. The MXML changes:

What happens? When the bindings execute, if a Mammal is selected, the mammal variable is equal to a Mammal instance and everything is smooth. If a Bird is selected, the mammal variable is null and everything is smooth again. Hurray! It took me about 2 hours to figure out. If you have a better solution, please share.

Previous: AIR Prerelease Tour Next: Instantiating and displaying MovieClips from loaded SWF