Using components, bindings, and custom formatters

Custom formatters help you format complex data in a specific way. You can also use custom formatting to help display images, HTML formatted text, or other components within a component such as the DataGrid. The following example illustrates how useful custom formatters can be.

To use custom formatters in a document:

  1. Create a new FLA file and add the DataBindingClasses class to the library (Window > Common Libraries > Classes).
  2. Drag a copy of the DateChooser component onto the Stage and give it the instance name my_dc.
  3. Drag a copy of the Label component onto the Stage and give it the instance name my_lbl.
  4. Insert a new layer and name it actions.
  5. Add the following ActionScript code to Frame 1 of the actions layer:
    import mx.data.binding.*;
    var src:EndPoint = new EndPoint();
    src.component = my_dc;
    src.property = "selectedDate";
    src.event = "change";
    var dest:EndPoint = new EndPoint();
    dest.component = my_lbl;
    dest.property = "text";
    new Binding(src, dest);
    

    This code creates a binding between the DateChooser's selectedDate property and the text property of the Label component on the Stage. Each time you click a new date in the calendar, the selected date appears in the Label component.

  6. Save the Flash document as customformat.fla in a convenient location on your hard disk.

    (You will recycle it in the next exercise.)

  7. Select Control > Test Movie to test the document.

    Try to change the dates in the Calendar component and you'll see the currently selected date appear in the Label component. The Label component isn't wide enough to display the entire date, so Flash crops off the text.

  8. Close the test SWF file and return to the authoring environment.

    Either resize the Label component on the Stage or select the Label component and set the autoSize property to left in the Parameters tab of the Property inspector.

  9. Select Control > Test Movie to test the document again.

    Now the text field displays the entire date, although it is awkward and lacks formatting. Depending on your own time zone and selected date, the date might appear similar to this: Thu Nov 4 00:00:00 GMT-0800 2004

    Even though the binding works properly and displays the selectedDate property, these dates aren't very user friendly. Nobody wants to see time-zone offsets, and you might not want to display hours, minutes, and seconds. What you need is a way to format the date so that it's more readable and a little less mechanical. Custom formatters are particularly useful for formatting text.

Formatting data using the CustomFormatter class

The CustomFormatter class defines two methods, format() and unformat(), that provide the ability to transform data values from a specific data type to String, and the reverse. By default, these methods do nothing; you must implement them in a subclass of mx.data.binding.CustomFormatter. The CustomFormatter class lets you convert data types to strings and back. In this case, you want to convert the selectedDate property from the DateChooser component into a nicely formatted string when the value copies into the Label component.

The following example shows you how to create your own custom formatter, which displays the date as NOV 4, 2004 instead of displaying a default date string.

NOTE

You need to complete the exercise from Using components, bindings, and custom formatters before you begin this one.

To format data using the CustomFormatter class:

  1. Select File > New and then select ActionScript File to create a new AS file.
  2. Select File > Save As and save the new file as DateFormat.as.
  3. Enter the following code into the Script window:
    class DateFormat extends mx.data.binding.CustomFormatter {
        function format(rawValue:Date):String {
            var returnValue:String;
            var monthName_array:Array = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
            returnValue = monthName_array[rawValue.getMonth()]+" "+rawValue.getDate()+", "+rawValue.getFullYear();
            return returnValue;
        }
    }
    

    The first section of code defines the new class called DateFormat, which extends the CustomFormatter class in the mx.data.binding package. Remember that Flash compiles the binding classes in the DataBindingClasses component file, so you can't view them directly or find them within the Classes folder in the Flash install directory.

    The only method you use is the format() method, which converts the date instance into a custom string format. The next step is to create an array of month names so that the end result looks closer to NOV 4, 2004 rather than the default date format. Remember that arrays are zero-based in Flash, so if the value of rawValue.getMonth() returns 1, it represents February instead of January (because January is month 0). The remaining code builds the custom formatted string by concatenating values and returning the returnValue string.

    A problem can arise when you work with classes within a compiled clip, which you can see in the previous snippet. Because you extend a class that's located in the DataBindingClasses class and it isn't readily available to Flash, you encounter the following error when you check the syntax in the previous class:

    **Error** <path to DateFormat class>\DateFormat.as: Line 1: The class 'mx.data.binding.CustomFormatter' could not be loaded.
         class DateFormat extends mx.data.binding.CustomFormatter {
    
    Total ActionScript Errors: 1      Reported Errors: 1
    

    Your code is probably fine. This problem occurs when Flash cannot locate the class, and because of this, syntax checking fails.

  4. Save the DateFormat.as file.
  5. Open customformat.fla from the exercise in Using components, bindings, and custom formatters. Make sure you save or copy DateFormat.as in the same directory as this file.
  6. In customformat.fla, modify the ActionScript code in Frame 1 of the actions layer to match the following code:
    import mx.data.binding.*;
    var src:EndPoint = new EndPoint();
    src.component = my_dc;
    src.property = "selectedDate";
    src.event = "change";
    var dest:EndPoint = new EndPoint();
    dest.component = my_lbl;
    dest.property = "text";
    new Binding(src, dest, {cls:mx.data.formatters.Custom, settings:{classname:"DateFormat", classname_class:DateFormat}});
    

    This time you define a customFormatter object, which tells Flash that you're using the newly created DateFormat class to format the endpoint on the binding.

  7. Save the changes in your document and select Control > Test Movie to test your code.