spark.collections

# Sort - AS3 Flex

Package | spark.collections
Class | public class Sort
Inheritance | Sort AdvancedStyleClient EventDispatcher Object
Implements | ISort

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 an existing view (`ICollectionView` interface or class that implements the interface). After you assign a `Sort` instance to the view's `sort` property, you must call the view's `refresh()` method to apply the sort criteria.

Typically the sort is defined for collections of complex items, that is collections in which the sort is performed on one or more properties of the objects in the collection. The following example shows this use:

         var col:ICollectionView = new ArrayCollection();
         // In the real world, the collection would have more than one item.
         col.addItem({first:"Anders", last:"Dickerson"});

         // Create the Sort instance.
         var sort:ISort = new Sort();

         // Set the sort field; sort on the last name first, first name second.
         var sortfieldLastName:ISortField = new SortField("last",true);
         var sortfieldFirstName:ISortField = new SortField("first",true);

         // Set the locale style to "en-US" to cause the strings
         // to be ordered according to the rules for English as used in the USA.
         sortfieldLastName.setStyle("locale","en-US");
         sortfieldFirstName.setStyle("locale","en-US");
         sort.fields = [sortfieldLastName, sortfieldFirstName];

         // Assign the Sort object to the view.
         col.sort = sort;

         // Apply the sort to the collection.
         col.refresh();

There are situations in which the collection contains simple items, like `String`, `Date`, `Boolean`, etc. In this case, apply the sort to the simple type directly. When constructing a sort for simple items, use a single sort field, and specify a `null` `name` (first) parameter in the SortField object constructor. For example:

         import mx.collections.ArrayCollection;
         import spark.collections.Sort;
         import spark.collections.SortField;

         var col:ICollectionView = new ArrayCollection();
         col.addItem("California");
         col.addItem("Arizona");
         var sort:Sort = new Sort();

         // There is only one sort field, so use a null
         // first parameter.
         var sortfield:SortField = new SortField("null",true);

         // Set the locale style to "en-US" to set the language for the sort.
         sortfield.setStyle("locale","en-US");
         sort.fields = [sortfield];
         col.sort = sort;
         col.refresh();

The Flex implementations of the `ICollectionView` interface retrieve all items from a remote location before executing a sort. If you use paging with a sorted list, apply the sort to the remote collection before you retrieve the data.

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 Syntax Show MXML Syntax
Hide MXML Syntax

The `<s:Sort>` tag has the following attributes:

      <s:Sort
      Properties
      compareFunction="Internal compare function"
      fields="null"
      unique="false | true"
      />

In case items have inconsistent data types or items have complex data types, use of default built-in compare functions is not desired. Inconsistent sort result may occur in such cases. To avoid such problem, provide custom compare function and/or make item types consistent.

Default MXML Property `fields`

View the examples

More examples

Sorting and filtering data for viewing
Sorting and matching

Related API Elements

mx.collections.ICollectionView
spark.collections.SortField

Public Properties
Hide Inherited Public Properties
Show Inherited Public Properties

| Property | Defined By
--- | --- | ---
|  | className : String [read-only] The name of the component class. | AdvancedStyleClient
|  | compareFunction : Function The method used to compare items when sorting. | Sort
|  | constructor : Object A reference to the class object or constructor function for a given object instance. | Object
|  | fields : Array An Array of ISortField objects that specifies the fields to compare. | Sort
|  | id : String The identity of the component. | AdvancedStyleClient
|  | inheritingStyles : Object An object containing the inheritable styles for this non-visual style client instance. | AdvancedStyleClient
|  | moduleFactory : 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
|  | nonInheritingStyles : Object The beginning of this component's chain of non-inheriting styles. | AdvancedStyleClient
|  | styleDeclaration : CSSStyleDeclaration The style declaration that holds the inline styles declared by this object. | AdvancedStyleClient
|  | styleManager : IStyleManager2 [read-only] Returns the StyleManager instance used by this component. | AdvancedStyleClient
|  | styleName : Object The source of this object's style values. | AdvancedStyleClient
|  | styleParent : IAdvancedStyleClient A component's parent is used to evaluate descendant selectors. | AdvancedStyleClient
|  | unique : Boolean Indicates if the sort should be unique. | Sort

Public Methods
Hide Inherited Public Methods
Show Inherited Public Methods

| Method | Defined By
--- | --- | ---
|  | Sort() Constructor. | Sort
|  | 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
|  | clearStyle(styleProp:String):void Deletes a style property from this component instance. | AdvancedStyleClient
|  | dispatchEvent(event:Event):Boolean Dispatches an event into the event flow. | EventDispatcher
|  | findItem(items:Array, values:Object, mode:String, returnInsertionIndex:Boolean = false, compareFunction:Function = null):int Finds the specified object within the specified array (or the insertion point if asked for), returning the index if found or -1 if not. | Sort
|  | getClassStyleDeclarations():Array Returns an Array of CSSStyleDeclaration objects for the type selector that applies to this component, or null if none exist. | AdvancedStyleClient
|  | getStyle(styleProp:String):* Gets a style property that has been set anywhere in this component's style lookup chain. | AdvancedStyleClient
|  | hasCSSState():Boolean Returns true if currentCSSState is not null. | AdvancedStyleClient
|  | hasEventListener(type:String):Boolean Checks whether the EventDispatcher object has any listeners registered for a specific type of event. | EventDispatcher
|  | hasOwnProperty(name:String):Boolean Indicates whether an object has a specified property defined. | Object
|  | initialized(document:Object, id:String):void The initialized method is called when this class or a class that extends this class is used in an MXML declaration. | AdvancedStyleClient
|  | isPrototypeOf(theClass:Object):Boolean Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter. | Object
|  | matchesCSSState(cssState:String):Boolean Returns true if cssState matches currentCSSState. | AdvancedStyleClient
|  | matchesCSSType(cssType:String):Boolean Determines whether this instance is the same as, or is a subclass of, the given type. | AdvancedStyleClient
|  | notifyStyleChangeInChildren(styleProp:String, recursive:Boolean):void Propagates style changes to the children of this style client instance. | AdvancedStyleClient
|  | propertyAffectsSort(property:String):Boolean Return whether the specified property is used to control the sort. | Sort
|  | propertyIsEnumerable(name:String):Boolean Indicates whether the specified property exists and is enumerable. | Object
|  | regenerateStyleCache(recursive:Boolean):void Sets up the internal style cache values so that the getStyle() method functions. | AdvancedStyleClient
|  | registerEffects(effects:Array):void Registers the EffectManager as one of the event listeners for each effect event. | AdvancedStyleClient
|  | removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void Removes a listener from the EventDispatcher object. | EventDispatcher
|  | reverse():void Goes through the fields array and calls reverse() on each of the ISortField objects in the array. | Sort
|  | setPropertyIsEnumerable(name:String, isEnum:Boolean = true):void Sets the availability of a dynamic property for loop operations. | Object
|  | setStyle(styleProp:String, newValue:*):void Sets a style property on this component instance. | AdvancedStyleClient
|  | sort(items:Array):void Apply the current sort to the specified array (not a copy). | Sort
|  | styleChanged(styleProp:String):void Detects changes to style properties. | AdvancedStyleClient
|  | stylesInitialized():void Flex calls the stylesInitialized() method when the styles for a component are first initialized. | AdvancedStyleClient
|  | toLocaleString():String Returns the string representation of this object, formatted according to locale-specific conventions. | Object
|  | toString():String Returns the string representation of the specified object. | Object
|  | valueOf():Object Returns the primitive value of the specified object. | Object
|  | willTrigger(type:String):Boolean Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. | EventDispatcher

Events
Click for more information on events
Hide Inherited Events
Show Inherited Events

| Event | Summary | Defined By
--- | --- | --- | ---
|  | activate | [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active. | EventDispatcher
|  | deactivate | [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
Click for more information on 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

http://www.unicode.org/reports/tr35/
Sort

Public Constants

| Constant | Defined By
--- | --- | ---
|  | ANY_INDEX_MODE : String = "any" [static] When executing a find return the index any matching item. | Sort
|  | FIRST_INDEX_MODE : String = "first" [static] When executing a find return the index for the first matching item. | Sort
|  | LAST_INDEX_MODE : String = "last" [static] When executing a find return the index for the last matching item. | Sort

Property Detail

### compareFunction

property

`compareFunction:Function`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 1.5

The method used to compare items when sorting. If you specify this property, Flex ignores any `compareFunction` properties that you specify in the `ISortField` objects that you use in this class.

The compare function must have the following signature:

             function [name](a:Object, b:Object, fields:Array = null):int

This function must return the following value:

- -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

To return to the internal comparision function, set this value to `null`.

The `fields` array specifies the object fields to compare. Typically the algorithm will compare properties until the field list is exhausted or a non-zero value can be returned. For example:

            function myCompare(a:Object, b:Object, fields:Array = null):int
            {
                var result:int = 0;
                var i:int = 0;
                var propList:Array = fields ? fields : internalPropList;
                var len:int = propList.length;
                var propName:String;
                while (result == 0 && (i < len))
                {
                    propName = propList[i];
                    result = compareValues(a[propName], b[propName]);
                    i++;
                }
                return result;
            }

            function compareValues(a:Object, b:Object):int
            {
                if (a == null && b == null)
                    return 0;

                if (a == null)
                  return 1;

                if (b == null)
                   return -1;

                if (a < b)
                    return -1;

                if (a > b)
                    return 1;

                return 0;
            }

The default value is an internal compare function that can perform a string, numeric, or date comparison in ascending or descending order. 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.

Alternatively you can specify separate compare functions for each sort field by using the `ISortField` class `compareFunction` property; This way you can use the default comparison for some fields and a custom comparison for others.

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

### fields

property

`fields:Array`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

An `Array` of `ISortField` objects that specifies the fields to compare. The order of the ISortField objects in the array determines field priority order when sorting. The default sort comparator checks the sort fields in array order until it determinines a sort order for the two fields being compared.

The default value is `null.`

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

Implementation
`public function get fields():Array`
`public function set fields(value:Array):void`

Related API Elements

SortField

### unique

property

`unique:Boolean`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 1.5

Indicates if the sort should be unique. Unique sorts fail if any value or combined value specified by the fields listed in the fields property result in an indeterminate or non-unique sort order; that is, if two or more items have identical sort field values. An error is thrown if the sort is not unique. The sorting logic uses this `unique` property value only if sort field(s) are specified explicitly. If no sort fields are specified explicitly, no error is thrown even when there are identical value elements.

The default value is `false.`

Implementation
`public function get unique():Boolean`
`public function set unique(value:Boolean):void`
Constructor Detail

### Sort

()
Constructor

`public function Sort()`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

Constructor.

Creates a new Sort with no fields set and no custom comparator.

Method Detail

### findItem

()
method

`public function findItem(items:Array, values:Object, mode:String, returnInsertionIndex:Boolean = false, compareFunction:Function = null):int`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

Finds the specified object within the specified array (or the insertion point if asked for), returning the index if found or -1 if not. The `ListCollectionView` class `findxxx()` methods use this method to find the requested item; as a general rule, it is easier to use these functions, and not `findItem()` to find data in `ListCollectionView`-based objects. You call the `findItem()` method directly when writing a class that supports sorting, such as a new `ICollectionView` implementation. The input items array need to be sorted before calling this function. Otherwise this function will not be able to find the specified value properly.

Parameters

| `items:Array` — the Array within which to search.
| `values:Object` — Object containing the properties to look for (or the object to search for, itself). The object must consist of field name/value pairs, where the field names are names of fields specified by the `fields` property, in the same order they are used in that property. You do not have to specify all of the fields from the `fields` property, but you cannot skip any in the order. Therefore, if the `fields` properity lists three fields, you can specify its first and second fields in this parameter, but you cannot specify only the first and third fields.
| `mode:String` — String containing the type of find to perform. Valid values are:

ANY_INDEX_MODE | Return any position that is valid for the values.
--- | ---
FIRST_INDEX_MODE | Return the position where the first occurrance of the values is found.
LAST_INDEX_MODE | Return the position where the last ocurrance of the specified values is found.

| `returnInsertionIndex:Boolean` (default = `false`)`` — If the method does not find an item identified by the `values` parameter, and this parameter is `true` the `findItem()` method returns the insertion point for the values, that is the point in the sorted order where you should insert the item.
| `compareFunction:Function` (default = `null`)`` — a comparator function to use to find the item. If you do not specify this parameter or , or if you provide a `null` value, `findItem()` function uses the compare function determined by the `ISort` instance's `compareFunction` property, passing in the array of fields determined by the values object and the current `SortFields`. If you provide a non-null value, `findItem()` function uses it as the compare function. The signature of the function passed as `compareFunction` must be as follows: `function myCompareFunction(a:Object, b:Object):int`. Note that there is no third argument unlike the compare function for `ISort.compareFunction()` property.

Returns

| `int` — int The index in the array of the found item. If the `returnInsertionIndex` parameter is `false` and the item is not found, returns -1. If the `returnInsertionIndex` parameter is `true` and the item is not found, returns the index of the point in the sorted array where the values would be inserted.

### propertyAffectsSort

()
method

`public function propertyAffectsSort(property:String):Boolean`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

Return whether the specified property is used to control the sort. The function cannot determine a definitive answer if the sort uses a custom comparator; it always returns `true` in this case.

Parameters

| `property:String` — The name of the field that to test.

Returns

| `Boolean` — Whether the property value might affect the sort outcome. If the sort uses the default compareFunction, returns `true` if the `property` parameter specifies a sort field. If the sort or any `ISortField` uses a custom comparator, there's no way to know, so return `true`.

### 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

Goes through the `fields` array and calls `reverse()` on each of the `ISortField` objects in the array. If the field was descending now it is ascending, and vice versa.

Note: an `ICollectionView` does not automatically update when the objects in the `fields` array are modified; call its `refresh()` method to update the view.

### sort

()
method

`public function sort(items:Array):void`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

Apply the current sort to the specified array (not a copy). To prevent the array from being modified, create a copy use the copy in the `items` parameter.

Flex `ICollectionView` implementations call the `sort` method automatically and ensure that the sort is performed on a copy of the underlying data.

Parameters

| `items:Array` — Array of items to sort.

Constant Detail

### ANY_INDEX_MODE

Constant

`public static const ANY_INDEX_MODE:String = "any"`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

When executing a find return the index any matching item.

### FIRST_INDEX_MODE

Constant

`public static const FIRST_INDEX_MODE:String = "first"`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

When executing a find return the index for the first matching item.

### LAST_INDEX_MODE

Constant

`public static const LAST_INDEX_MODE:String = "last"`

Language Version: | ActionScript 3.0

Product Version: | Flex 4.5

Runtime Versions: | Flash Player 10.1, AIR 2.5

When executing a find return the index for the last matching item.

Examples How to use this example
SortExample1.mxml
Copy

    <?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
Copy

    <?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>

© 2015 Adobe Systems Incorporated. All rights reserved.
Mon Apr 10 2017, 12:28 PM -07:00