Packagespark.collections
Classpublic class Sort
InheritanceSort Inheritance Sort Inheritance flash.events.EventDispatcher
Implements IAdvancedStyleClient, IFlexModule, IMXMLObject

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 setting the locale style on an instance of the class in one of the following ways:

Note: to prevent problems like FLEX-34853 it is recommended to use SortField instances as immutable objects (by not changing their state).

MXML SyntaxexpandedHide 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, the use of the default built-in compare functions is not recommended. Inconsistent sorting results may occur in such cases. To avoid such problem, provide a custom compare function and/or make the item types consistent.

Default MXML Propertyfields

View the examples

See also

mx.collections.ICollectionView
spark.collections.SortField


Public Properties
 PropertyDefined By
  className : String
[read-only]
Sort
 InheritedcompareFunction : Function
The method used to compare items when sorting.
Sort
 Inheritedfields : Array
An Array of ISortField objects that specifies the fields to compare.
Sort
  id : String
Sort
  inheritingStyles : Object
Sort
  moduleFactory : IFlexModuleFactory
Sort
  nonInheritingStyles : Object
Sort
  styleDeclaration : CSSStyleDeclaration
Sort
  styleManager : IStyleManager2
[read-only]
Sort
  styleName : Object
Sort
  styleParent : IAdvancedStyleClient
Sort
 Inheritedunique : Boolean
Indicates if the sort should be unique.
Sort
Public Methods
 MethodDefined By
  
Sort(fields:Array = null, customCompareFunction:Function = null, unique:Boolean = false)
Constructor.
Sort
  
clearStyle(styleProp:String):void
Sort
 Inherited
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
  
Sort
  
getStyle(styleProp:String):*
Sort
  
hasCSSState():Boolean
Sort
  
initialized(document:Object, id:String):void
Sort
  
matchesCSSState(cssState:String):Boolean
Sort
  
matchesCSSType(cssType:String):Boolean
Sort
  
notifyStyleChangeInChildren(styleProp:String, recursive:Boolean):void
Sort
 Inherited
propertyAffectsSort(property:String):Boolean
Return whether the specified property is used to control the sort.
Sort
  
regenerateStyleCache(recursive:Boolean):void
Sort
  
registerEffects(effects:Array):void
Sort
 Inherited
reverse():void
Goes through the fields array and calls reverse() on each of the ISortField objects in the array.
Sort
  
setStyle(styleProp:String, newValue:*):void
Sort
 Inherited
sort(items:Array):void
Apply the current sort to the specified array (not a copy).
Sort
  
styleChanged(styleProp:String):void
Sort
  
Sort
Protected Methods
 MethodDefined By
  
[override]
Sort
Styles
 Style Description Defined By
  
locale
Type: String CSS Inheritance: yes
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.

See also

Sort
Public Constants
 ConstantDefined 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
classNameproperty
className:String  [read-only]


Implementation
    public function get className():String
idproperty 
id:String


Implementation
    public function get id():String
    public function set id(value:String):void
inheritingStylesproperty 
inheritingStyles:Object


Implementation
    public function get inheritingStyles():Object
    public function set inheritingStyles(value:Object):void
moduleFactoryproperty 
moduleFactory:IFlexModuleFactory


Implementation
    public function get moduleFactory():IFlexModuleFactory
    public function set moduleFactory(value:IFlexModuleFactory):void
nonInheritingStylesproperty 
nonInheritingStyles:Object


Implementation
    public function get nonInheritingStyles():Object
    public function set nonInheritingStyles(value:Object):void
styleDeclarationproperty 
styleDeclaration:CSSStyleDeclaration


Implementation
    public function get styleDeclaration():CSSStyleDeclaration
    public function set styleDeclaration(value:CSSStyleDeclaration):void
styleManagerproperty 
styleManager:IStyleManager2  [read-only]


Implementation
    public function get styleManager():IStyleManager2
styleNameproperty 
styleName:Object


Implementation
    public function get styleName():Object
    public function set styleName(value:Object):void
styleParentproperty 
styleParent:IAdvancedStyleClient


Implementation
    public function get styleParent():IAdvancedStyleClient
    public function set styleParent(value:IAdvancedStyleClient):void
Constructor Detail
Sort()Constructor
public function Sort(fields:Array = null, customCompareFunction:Function = null, unique:Boolean = false)

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.

Parameters
fields:Array (default = null) — An Array of ISortField objects that specifies the fields to compare.
 
customCompareFunction:Function (default = null) — Use a custom function to compare the objects in the collection to which this sort will be applied.
 
unique:Boolean (default = false) — Indicates if the sort should be unique.
Method Detail
clearStyle()method
public function clearStyle(styleProp:String):void

Parameters

styleProp:String

createEmptySortField()method 
override protected function createEmptySortField():ISortField

Returns
ISortField
getClassStyleDeclarations()method 
public function getClassStyleDeclarations():Array

Returns
Array
getStyle()method 
public function getStyle(styleProp:String):*

Parameters

styleProp:String

Returns
*
hasCSSState()method 
public function hasCSSState():Boolean

Returns
Boolean
initialized()method 
public function initialized(document:Object, id:String):void

Parameters

document:Object
 
id:String

matchesCSSState()method 
public function matchesCSSState(cssState:String):Boolean

Parameters

cssState:String

Returns
Boolean
matchesCSSType()method 
public function matchesCSSType(cssType:String):Boolean

Parameters

cssType:String

Returns
Boolean
notifyStyleChangeInChildren()method 
public function notifyStyleChangeInChildren(styleProp:String, recursive:Boolean):void

Parameters

styleProp:String
 
recursive:Boolean

regenerateStyleCache()method 
public function regenerateStyleCache(recursive:Boolean):void

Parameters

recursive:Boolean

registerEffects()method 
public function registerEffects(effects:Array):void

Parameters

effects:Array

setStyle()method 
public function setStyle(styleProp:String, newValue:*):void

Parameters

styleProp:String
 
newValue:*

styleChanged()method 
public function styleChanged(styleProp:String):void

Parameters

styleProp:String

stylesInitialized()method 
public function stylesInitialized():void

Constant Detail
ANY_INDEX_MODEConstant
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_MODEConstant 
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_MODEConstant 
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
SortExample1.mxml
<?xml version="1.0" encoding="utf-8"?>
<!--

  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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