Interactive Development specialising in web-applications
Helper Method for Handling Flash Vars in Flex
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.
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:
123456789
package com.newtriks.services
{
import flash.events.IEventDispatcher;
public interface IExternalParametersService
{
function loadParameters():void;
}
}
And the APIData Object looks like this:
1234567891011121314151617
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:
12
/** Flash Vars passed into Flex **/
var flashvars = {username:"newtriks",role:"admin",status:"1"};