Avg. Rating 3.4

Problem

To select a view in a ViewStack you usually have two possibilities: Using its id or using its index in the ViewStack. Both solutions have their drawbacks: Using the index you have to maintain constants that relate the index to a readable name and using ids you have to maintain an id for each view. So why you are not using the Class of the view for selection?

Solution

To use the Class for the selection of the view, you have to build a helper function that looks up the index of the view by its Class. This is done by iterating over all ComponentDescriptors of the ViewStack and returning the index of the one whose type value is matching to the Class.

Detailed explanation

First let's take a look at the helper function:

private function getView(viewClass:Class):int {
  var descriptors:Array = views.childDescriptors;
  for (var i:int=0; i<descriptors.length; i++) {
    var descriptor:ComponentDescriptor = descriptors[i];
    if(viewClass==descriptor.type) return i;
  }
  throw new Error( "View of " + viewClass + " not found.");
}

Here's an example how to use this helper function:

First we need a variable, where we can store the class of the actual view, let's name it actualView:

[Bindable]
public var actualView:Class = FirstView;

(best practice pattern would be to store this variable in a extra Singleton, so we can change its value from everywhere)

Then we can use both, the actualView and the helper function to get the index of the actual view:

<mx:ViewStack id="views" selectedIndex="{getView(actualView )}">
<view:FirstView/>
<view:SecondView/>
...
</mx:ViewStack>

As we are using data binding, to change the view we just have to call:

actualView = SecondView;

Report abuse

Related recipes