ActionScript® 3.0 Reference for the Adobe® Flash® Platform
Home  |  Show Packages and Classes List |  Packages  |  Classes  |  What's New  |  Index  |  Appendixes
spark.collections 

SortField  - AS3 Flex

Packagespark.collections
Classpublic class SortField
InheritanceSortField Inheritance AdvancedStyleClient Inheritance EventDispatcher Inheritance Object
Implements ISortField

Language Version: ActionScript 3.0
Product Version: Flex 4.5
Runtime Versions: Flash Player 10.1, AIR 2.5

Provides the sorting information required to establish a sort on a field or property in a collection view. SortField class is meant to be used with Sort class. Typically the sort is defined for collections of complex items, that is items in which the sort is performed on properties of those objects. As in the following example:

     var col:ICollectionView = new ArrayCollection();
     col.addItem({first:"Anders", last:"Dickerson"});
     var sort:Sort = new Sort();
     var sortfield:SortField = new SortField("first", true);
     sortfield.setStyle("locale", "en-US");
     sort.fields = [sortfield];
     col.sort = sort;
  
There are situations in which the collection contains simple items, like String, Date, Boolean, etc. In this case, sorting should be applied to the simple type directly. When constructing a sort for this situation only a single sort field is required and should not have a name specified. For example:

     var col:ICollectionView = new ArrayCollection();
     col.addItem("California");
     col.addItem("Arizona");
     var sort:Sort = new Sort();
     var sortfield:SortField = new SortField(null, true);
     sortfield.setStyle("locale", "en-US");
     sort.fields = [sortfield];
     col.sort = sort;
  

The default comparison provided by the SortField class provides correct language specific sorting for strings. The language is selected by the setting the locale style on an instance of the class in one of the following ways:

  • By using the class in an MXML declaration and inheriting the locale from the document that contains the declaration.
  • Example:
  <fx:Declarations> 
         <s:SortField id="sf" /> 
  </fx:Declarations>
  
  • By using an MXML declaration and specifying the locale value in the list of assignments.
  • Example:
      <fx:Declarations> 
          <s:SortField id="sf_SimplifiedChinese" locale="zh-Hans-CN" /> 
      </fx:Declarations>
      
  • Calling the setStyle method, e.g. sf.setStyle("locale", "zh-Hans-CN")
  • Inheriting the style from a UIComponent by calling the UIComponent's addStyleClient() method.
  • MXML SyntaxexpandedHide MXML Syntax

    The <s:SortField> tag has the following attributes:

      <s:SortField
      Properties
      compareFunction="Internal compare function"
      descending="false"
      name="null"
      numeric="null"
      />
      

    View the examples

    More examples

    Related API Elements



    Public Properties
     PropertyDefined By
      arraySortOnOptions : int
    [read-only] This helper property is used internally by the findItem() and sort() methods.
    SortField
     InheritedclassName : String
    [read-only] The name of the component class.
    AdvancedStyleClient
      compareFunction : Function
    The function that compares two items during a sort of items for the associated collection.
    SortField
     Inheritedconstructor : Object
    A reference to the class object or constructor function for a given object instance.
    Object
      descending : Boolean
    Specifies whether this field should be sorted in descending order.
    SortField
     Inheritedid : String
    The identity of the component.
    AdvancedStyleClient
     InheritedinheritingStyles : Object
    An object containing the inheritable styles for this non-visual style client instance.
    AdvancedStyleClient
     InheritedmoduleFactory : IFlexModuleFactory
    A module factory is used as context for finding the style manager that controls the styles for this non-visual style client instance.
    AdvancedStyleClient
      name : String
    The name of the field to be sorted.
    SortField
     InheritednonInheritingStyles : Object
    The beginning of this component's chain of non-inheriting styles.
    AdvancedStyleClient
      numeric : Object
    Specifies that if the field being sorted contains numeric (number/int/uint) values, or string representations of numeric values, the comparator use a numeric comparison.
    SortField
     InheritedstyleDeclaration : CSSStyleDeclaration
    The style declaration that holds the inline styles declared by this object.
    AdvancedStyleClient
     InheritedstyleManager : IStyleManager2
    [read-only] Returns the StyleManager instance used by this component.
    AdvancedStyleClient
     InheritedstyleName : Object
    The source of this object's style values.
    AdvancedStyleClient
     InheritedstyleParent : IAdvancedStyleClient
    A component's parent is used to evaluate descendant selectors.
    AdvancedStyleClient
      usingCustomCompareFunction : Boolean
    [read-only] True if this ISortField uses a custom comparator function.
    SortField
    Public Methods
     MethodDefined By
      
    SortField(name:String = null, descending:Boolean = false, numeric:Object = null)
    Constructor.
    SortField
     Inherited
    addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
    Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
    EventDispatcher
     Inherited
    Deletes a style property from this component instance.
    AdvancedStyleClient
     Inherited
    Dispatches an event into the event flow.
    EventDispatcher
     Inherited
    Returns an Array of CSSStyleDeclaration objects for the type selector that applies to this component, or null if none exist.
    AdvancedStyleClient
     Inherited
    getStyle(styleProp:String):*
    Gets a style property that has been set anywhere in this component's style lookup chain.
    AdvancedStyleClient
     Inherited
    Returns true if currentCSSState is not null.
    AdvancedStyleClient
     Inherited
    Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
    EventDispatcher
     Inherited
    Indicates whether an object has a specified property defined.
    Object
     Inherited
    The initialized method is called when this class or a class that extends this class is used in an MXML declaration.
    AdvancedStyleClient
      
    A helper function called by the Sort class to set the default comparison function to perform a comparison based on one of three things: whether or not a custom compare function has been set, the data type for the specified field or the the value of the numeric property.
    SortField
     Inherited
    Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
    Object
     Inherited
    Returns true if cssState matches currentCSSState.
    AdvancedStyleClient
     Inherited
    Determines whether this instance is the same as, or is a subclass of, the given type.
    AdvancedStyleClient
     Inherited
    Propagates style changes to the children of this style client instance.
    AdvancedStyleClient
     Inherited
    Indicates whether the specified property exists and is enumerable.
    Object
     Inherited
    Sets up the internal style cache values so that the getStyle() method functions.
    AdvancedStyleClient
     Inherited
    Registers the EffectManager as one of the event listeners for each effect event.
    AdvancedStyleClient
     Inherited
    removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
    Removes a listener from the EventDispatcher object.
    EventDispatcher
      
    Reverse the criteria for this sort field.
    SortField
     Inherited
    Sets the availability of a dynamic property for loop operations.
    Object
     Inherited
    setStyle(styleProp:String, newValue:*):void
    Sets a style property on this component instance.
    AdvancedStyleClient
     Inherited
    Detects changes to style properties.
    AdvancedStyleClient
     Inherited
    Flex calls the stylesInitialized() method when the styles for a component are first initialized.
    AdvancedStyleClient
     Inherited
    Returns the string representation of this object, formatted according to locale-specific conventions.
    Object
     Inherited
    Returns the string representation of the specified object.
    Object
     Inherited
    Returns the primitive value of the specified object.
    Object
     Inherited
    Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
    EventDispatcher
    Events
     Event Summary Defined By
     Inherited[broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
     Inherited[broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
    Styles

    Styles are either common or associated with a specific theme. If the style is common, it can be used with any theme. If a style is associated with a specific theme, it can only be used if your application uses that theme.

    Common Styles
     Style Description Defined By
      
    locale
    Type: String CSS Inheritance: Yes
    Language Version: ActionScript 3.0  Product Version: Flex 4.5  Runtime Versions: Flash10.1, AIR 2.5

    The locale identifier that specifies the language, region, script and optionally other related tags and keys. The syntax of this identifier must follow the syntax defined by the Unicode Technical Standard #35 (for example, en-US, de-DE, zh-Hans-CN).

    For browser based apps, the default locale is based on the language settings from the browser. (Note that this is not the browser UI language that is available from Javascript, but rather is the list of preferred locales for web pages that the user has set in the browser preferences.) For AIR applications, the default UI locale is based on the user's system preferences.

    Learn more

    SortField
    Property Detail

    arraySortOnOptions

    property
    arraySortOnOptions:int  [read-only]

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    This helper property is used internally by the findItem() and sort() methods. Other uses of this property are not supported. Returns -1 if this ISortField shouldn't be used by the Sort class to sort the field (there is no compareFunction or no name). Otherwise, returns a bitmask of sort options..



    Implementation
        public function get arraySortOnOptions():int

    compareFunction

    property 
    compareFunction:Function

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    The function that compares two items during a sort of items for the associated collection. If you specify a compareFunction property in an ISort object, Flex ignores any compareFunction properties of the ISort's SortField objects.

    The compare function must have the following signature:

    function myCompare(a:Object, b:Object):int

    This function must return the following values:

    • -1, if the Object a should appear before the Object b in the sorted sequence
    • 0, if the Object a equals the Object b
    • 1, if the Object a should appear after the Object b in the sorted sequence

    The default value is an internal compare function that can perform a string, numeric, or date comparison in ascending or descending order. The string comparison is performed using the locale (language, region and script) specific comparison method from the SortingCollator class. This class uses the locale style to determine a locale Specify your own function only if you need a need a custom comparison algorithm. This is normally only the case if a calculated field is used in a display.



    Implementation
        public function get compareFunction():Function
        public function set compareFunction(value:Function):void

    descending

    property 
    descending:Boolean

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    Specifies whether this field should be sorted in descending order.

    The default value is false (ascending).

    This property can be used as the source for data binding. When this property is modified, it dispatches the descendingChanged event.



    Implementation
        public function get descending():Boolean
        public function set descending(value:Boolean):void

    name

    property 
    name:String

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    The name of the field to be sorted.

    The default value is null.

    This property can be used as the source for data binding. When this property is modified, it dispatches the nameChanged event.



    Implementation
        public function get name():String
        public function set name(value:String):void

    numeric

    property 
    numeric:Object

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    Specifies that if the field being sorted contains numeric (number/int/uint) values, or string representations of numeric values, the comparator use a numeric comparison.

    This property is used by SortField class in case custom compare function is not provided.

    If this property is true, the built-in numeric compare function is used. Each of data items is cast to a Number() function before the comparison.

    If this property is false, the built-in string compare function is used. Each of data items is cast to a String() function before the comparison.

    If this property is null, the first data item is introspected to see if it is a number or string and the sort proceeds based on that introspection.

    The default value is null.

    This property can be used as the source for data binding. When this property is modified, it dispatches the numericChanged event.



    Implementation
        public function get numeric():Object
        public function set numeric(value:Object):void

    usingCustomCompareFunction

    property 
    usingCustomCompareFunction:Boolean  [read-only]

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    True if this ISortField uses a custom comparator function.



    Implementation
        public function get usingCustomCompareFunction():Boolean
    Constructor Detail

    SortField

    ()Constructor
    public function SortField(name:String = null, descending:Boolean = false, numeric:Object = null)

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    Constructor.

    Parameters
    name:String (default = null) — The name of the property that this field uses for comparison. If the object is a simple type, pass null.
     
    descending:Boolean (default = false) — Tells the comparator whether to arrange items in descending order.
     
    numeric:Object (default = null) — Tells the comparator whether to compare sort items as numbers, instead of alphabetically.
    Method Detail

    initializeDefaultCompareFunction

    ()method
    public function initializeDefaultCompareFunction(obj:Object):void

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    A helper function called by the Sort class to set the default comparison function to perform a comparison based on one of three things: whether or not a custom compare function has been set, the data type for the specified field or the the value of the numeric property. If the the numeric property is true, then a numeric comparison will be performed when sorting.

    Parameters

    obj:Object — The object that contains the data. If the field name has been set with the name property, then the name will be used to access the data value from this object. Otherwise the object itself will be used as the data value.

    reverse

    ()method 
    public function reverse():void

    Language Version: ActionScript 3.0
    Product Version: Flex 4.5
    Runtime Versions: Flash Player 10.1, AIR 2.5

    Reverse the criteria for this sort field. If the field was sorted in descending order, for example, sort it in ascending order.

    NOTE: An ICollectionView does not automatically update when the ISortFields are modified; call its refresh() method to update the view.

    SortExample1.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" 
                   minWidth="955" minHeight="600">
        <!-- Sample program for spark.collections.Sort and SortField --> 
        <fx:Declarations>
            <s:Sort id="sortbyLastName_FirstName">
                <s:fields>
                    <s:SortField name="last"/>
                    <s:SortField name="first"/>
                </s:fields>
            </s:Sort>
            <mx:ArrayCollection id="collection" sort="{sortbyLastName_FirstName}">
                <mx:source>
                    <fx:Object first="Anders" last="Dickerson"/>
                    <fx:Object first="Eileen" last="Maccormick"/>
                    <fx:Object first="Aiden" last="MacCormick"/>
                    <fx:Object first="Steve" last="MacGregor"/>
                </mx:source>
            </mx:ArrayCollection>
        </fx:Declarations>
        
        <s:VGroup>
            <s:VGroup>
                <s:HGroup>
                    <s:Label text="Input Locale ID Name: "/>
                    <s:TextInput id="inputLocaleIDName"/>
                    <!-- 
                    Sets the locale style on the document UI component.
                    The SortField and Sort objects defined in the 
                    fx:Declarations section will inherit this style.
                    -->
                    <s:Button click="{setStyle('locale', inputLocaleIDName.text); 
                              collection.refresh()}" label="Apply"/>
                </s:HGroup>
                <s:Label text="Example: 'en-US', 'fr-FR', 'zh-CN', 'ar-SA'"/>
            </s:VGroup>
            <s:DataGrid dataProvider="{collection}" width="100%"
                         creationComplete="{collection.refresh()}">
                <s:columns>
                    <s:ArrayList>
                        <s:GridColumn dataField="last"/>
                        <s:GridColumn dataField="first"/>
                    </s:ArrayList>
                </s:columns>
            </s:DataGrid>
        </s:VGroup>
    </s:Application>
    
    SortExample2.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" 
                   minWidth="955" minHeight="600"
                   creationComplete="initApp()">
        <!-- Sample program for spark.collections.Sort and SortField -->    
        <fx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import spark.collections.*;
                [Bindable]
                private var collection:ArrayCollection = new ArrayCollection();
                
                private function localeChange():void
                {
                    // Sets the locale style on this application.
                    // The SortField objects will inherit this style.
                    setStyle('locale', inputLocaleIDName.text);
                    collection.refresh();
                }
    
                private function initApp() : void
                {
                    // Add data to the collection.
                    collection.addItem({first:"Anders", last:"Dickerson"});
                    collection.addItem({first:"Steve", last:"Maccormick"});
                    collection.addItem({first:"Aiden", last:"MacCormick"});
                    collection.addItem({first:"Eileen", last:"MacGregor"});
                    
                    // Create the Sort instance.
                    var sort:Sort = new Sort();
                    
                    // Set the sort field; sort on the last name first, first name 
                    // second.
                    var sortfieldLastName:SortField = new SortField("last",true);
                    var sortfieldFirstName:SortField = new SortField("first",true);
                    sort.fields = [sortfieldLastName, sortfieldFirstName];
                    
                    // Add the sort field objects to this application's list of
                    // style clients.  This will cause the sort field objects to 
                    // inherit the locale style from this Application. 
                    addStyleClient(sortfieldLastName);
                    addStyleClient(sortfieldFirstName);
                    
                    // Assign the Sort object to the view.
                    collection.sort = sort;
                    
                    // Apply the sort to the collection.
                    collection.refresh();
                }
            ]]>
        </fx:Script>
        
        <s:VGroup>
            <s:VGroup>
                <s:HGroup>
                    <s:Label text="Input Locale ID Name: "/>
                    <s:TextInput id="inputLocaleIDName"/>
                    <s:Button click="localeChange()" label="Apply"/>
                </s:HGroup>
                <s:Label text="Example: 'en-US', 'fr-FR', 'zh-CN', 'ar-SA'"/>
            </s:VGroup>
            
            <s:DataGrid dataProvider="{collection}" width="100%"
                         creationComplete="{collection.refresh()}">
                <s:columns>
                    <s:ArrayList>
                        <s:GridColumn dataField="last"/>
                        <s:GridColumn dataField="first"/>
                    </s:ArrayList>
                </s:columns>
            </s:DataGrid>
        </s:VGroup>
    </s:Application>