Flex offerers a wide range of utilities to make working with complicated components and applications simpler. One such feature is the use of States. States are often thought of as only visual or GUI related, but in they are perfect for dividing up logic. In my current project I am building a series of learning activities, and some have activities within activities… needless to say it can get complicated quickly. While breaking up the logic into separate components was one option, I didn’t want to have any risk of ‘flashes’ of GUI while pieces are refreshed, moved, or risk messing up data by passing all these pieces around.
I started to build out my activity component using states. One state for when you enter the activity, one for each of the three phases, a cleanup state and finally an exiting state. As I developed the components and created their enterState and exitState functions, as well as many functions only used while in a specific state, I realized that my component was getting to be well over a thousand lines of code and a bit unmanageable. To find the logic pertaining to the current section I was working on, I had to sift through hundreds of lines of code. I decided there had to be a better way… and there was!
I started by creating an AbstractActivityState that extended the State class. This had had any common properties and logic, as well as a bindable “Activity” object. This worked well for accessing the public variables of the activity. The problem came with private variables. While I would have had access to these if I had written all my logic within the Activity MXML, since I was passing the Activity object into my states, they were inaccessible.
There were three solutions I found for this problem:
- Make all the properties you need access to within the state public, and break encapsulation rules.
- Add additional Bindable properties to the the custom state classes and pass in the bindable private variables.
- Create a StateMiniModel that had all the bindable properties I needed and simply pass it to the custom state. This is handy if you don’t want to break encapsulation but have a great many common private variables to be passed to all your custom classes.
To make things even more simple, I added some listeners and protected ‘enter/exit’ classes to be called from within the AbstractActivityState so I when declaring my states in MXML I didn’t need to give it anything other than a name.