This is the follow up to a post I wrote a little while ago.
Eliminate the Metadata tag
In the past I was accessing the resource bundle directly in the class. This meant that in I had to add the Metadata tag in every file. A better approach is to create a static class which calls ResourceManager.getInstance(). This way only this class needs to have the Metadata for the bundles. Here’s the static class I’m using.
package { import mx.resources.ResourceManager; [ResourceBundle("People")] [ResourceBundle("Groups")] [ResourceBundle("Framework")] public class ResourceUtils { public static function getString( module:String, key:String, failSilently:Boolean = false ):String { var value:String = ResourceManager.getInstance().getString( module, key ); if (!value) { value = ResourceManager.getInstance().getString( "Framework", key ); } if (!value && !failSilently) { throw new Error( "Error: failed to find value for " + key + " in " + bundleName + " resource bundle" ); } return value ? value : ""; } } }
The application that I’m working on is divided into a number of modules, each has their own resource file. To support this, when requesting a string you also specify the module. If the value isn’t found in the module resource file, then we check the overall framework resource file.
Throw an error if a value isn’t found
I find that I pretty often mistype a key for a string. The default behavior in Flex is to return null, I prefer throw an error in this case as it makes tracking down any missing values much easier. I’ve added the failSilently flag for cases where they may not be a value.
Here’s an example of how you’d use it
<mx:Label text="{ ResourceUtils.getString( Consts.MODULE_PEOPLE, 'addButton' ) }"/>
Static classes for resources in general
This idea of using static classes to reference resources also works well for images. I just saw this in a book I’m reading AdvancED Flex Application Development. It’s a nice, clean approach.
package { [Bindable] public class AssetLib { [Embed(source="buttonUpSkin.png")] public static var buttonUpImage:Class; [Embed(source="buttonDownSkin.png")] public static var buttonDownImage:Class; } }
Hope you find this useful,
Hillel
I bookmarked your site, this is very useful, thank you. Please check mine : crm – customer resource management