Helper Method for Handling Flash Vars in Flex

Written by

I have used the below logic repeatedly now for processing Flash Vars in my Flex 4 applications which others may find useful. In the example below I use it in a service class. Basically I define a custom value object with the flash var properties defined. I then loop through the available parameters in the loadParameters() method using a [Transient] array which returns the name of each parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.newtriks.services
{ 
  import com.newtriks.models.vo.APIData;
  import flash.events.EventDispatcher;    
  import mx.core.FlexGlobals;
  
  public class FlashVarsService extends EventDispatcher implements IExternalParametersService
  {
      public function FlashVarsService(){}
      
      public function loadParameters():void
      {
          var flashVars:Object = FlexGlobals.topLevelApplication.parameters;
          var data:APIData = new com.newtriks.models.vo.APIData();
          var param:String;
          var i:int;
          var length:int = data.params.length-1;
          
          for ( i = length; i >= 0; i -- )
          {
              param = data.params[i].toString();
              
              if(flashVars[param] != null)
                  data[param] = flashVars[param]; 
              else
                  data[param] = ""; // Simply populate a null param with an empty string
          }
      }
  }
}

Which implements:

1
2
3
4
5
6
7
8
9
package com.newtriks.services
{
  import flash.events.IEventDispatcher;

  public interface IExternalParametersService
  {
      function loadParameters():void;
  }
}

And the APIData Object looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.newtriks.models.vo
{
  public class APIData
  {
      public var username:String = '';
      public var role:String = '';
      public var status:String = '';
      
      public function APIData(){}
      
      [Transient] 
      public function get params():Array 
      { 
          return ["username","role","status"]; 
      }
  }
}

And finally the actual Flash Vars in the html wrapper:

1
2
/** Flash Vars passed into Flex **/
var flashvars = {username:"newtriks",role:"admin",status:"1"};

Comments