Creating a custom formatter
Posted on May 28, 2010 | No Comments
You create a custom formatter by creating a class that extends the mx.formatters.Formatter base class, or by creating a class that extends one of the standard formatter classes, which all extend mx.formatters.Formatter. The following example shows the class hierarchy for formatters:
Like standard formatter classes, your custom formatter class must contain a public format() method that takes a single argument and returns a String that contains the formatted data. Most of the processing of your custom formatter occurs within the format() method.
Your custom formatter also might let the user specify which pattern formats the data. Where applicable, the Flex formatters, such as the ZipCodeFormatter, use a formatString property to pass a format pattern. Some Flex formatters, such as the NumberFormatter and CurrencyFormatter classes, do not have formatString properties, because they use a set of properties to configure formatting.
Creating a simple formatter
This example defines a simple formatter class that converts any String to all uppercase or all lowercase letters depending on the value passed to the formatString property. By default, the formatter converts a String to all uppercase.
package myFormatters { // SimpleFormatter.as import mx.formatters.Formatter import mx.formatters.SwitchSymbolFormatter public class SimpleFormatter extends Formatter { // Declare the variable to hold the pattern string. public var myFormatString:String = "upper"; // Constructor public function SimpleFormatter() { // Call base class constructor. super(); } // Override format(). override public function format(value:Object):String { // 1. Validate value - must be a nonzero length string. if( value.length == 0) { error="0 Length String"; return "" } // 2. If the value is valid, format the string. switch (myFormatString) { case "upper" : var upperString:String = value.toUpperCase(); return upperString; break; case "lower" : var lowerString:String = value.toLowerCase(); return lowerString; break; default : error="Invalid Format String"; return "" } } } }
You can use this formatter in a Flex application, as the following example shows:
<?xml version="1.0" ?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:MyComp="myFormatters.*"> <!-- Declare a formatter and specify formatting properties. --> <MyComp:SimpleFormatter id="upperFormat" myFormatString="upper" /> <!-- Trigger the formatter while populating a string with data. --> <mx:TextInput id="myTI" /> <mx:TextArea text="Your uppercase string is {upperFormat.format(myTI.text)}" /> </mx:Application>
Comments
Leave a Reply
You must be logged in to post a comment.