I am using Adobe Flex at work to build an internet application. This application is available in multiple languages and the user should be able to switch the language on the fly, no restart of the app should be neccessary.
We save out internationalised data in XML files, the usual way to save this kind of stuff seem to be ressource bundles, but for what I want to show that doesn't matter.
Until now we had a really cumbersome way to replace all the labels and so on. After beeing quite annoyed by that while translating my app I searched the web for alternative ways and found out the following.
One of the best things about Flex is the extensive use of databindings. For example you can bind texts to variables or functions.
This in combination with a function which listens for an event and whoosh, you have your self-updating application on language change.
Here is some code to make this more clear:
View.mxml
<mx:button label="{I18n.getText('module', 'key')}" />
ActionScript Class I18n:
public class I18n extends EventDispatcher
{
[...]
private var currentLanguage:String = "de";
[Bindable(event="languageChanged")]
public function getText(module:String, key:String):String
{
return getTextFromXML(module, text);
}
public function changeLanguage(language:String):void
{
this.currentLanguage = language;
this.dispatchEvent(new Event("languageChanged"));
}
}
In the MXML file the function I18n:getText is bound to the label property of the button component. The function is calling another function which gets the text identified by the currently selected language (currentLanguage), the module and the key from an XML file. How you implement this is up to you, this is just how we do it.
The important part of getText is the line above it: [Bindable(event="languageChanged")]. This means that the function listens for an event of the type "languageChanged". Once that event is dispatched all values bound to the getText function are updated.
The function changeLanguage is called when the selected language is changed. The language is set to the new selected language and a languageChanged event is fired. To do this, the class I18n has to extend EventDispatcher.
And that's all there is to it, simple but effective ;)
Tags: adobe · code · dynamic · example · flex · i18n · internationalisation · language · programming
