Follow Flex After Dark on Twitter

Flex Collections (ArrayCollection and XMLListCollection)

Collections are objects that provide a uniform way to access and represent the data/items contained in a source object, such as an Array or an XMLList object. Collections provide a level of abstraction between Flex components and the source objects that you use to populate them.

Collections provide the following high-level features and benefits:

  • Collections provide a consistent set of operations for manipulating underlying data, regardless of type
  • Collections as data providers ensure that components are properly updated when their data changes
  • Collections can provide a filtered and sorted view of their underlying data

Collection Implementations

Two useful collection implementations, ArrayCollection and XMLListCollection, are provided by Flex in the mx.collections package.

Collections provide a consistent set of operations for manipulating data, independent of the underlying source object. For example, you can insert and delete objects by using an index into the collection, independently of whether the underlying data is, for example, in an Array, an Object, or XML.

Learn more about the ArrayCollection class...

Collection Properties, Methods, and Events

Commonly useful collection properties:

  • length - the number of items in a collection
  • filterFunction - the function used to filter collection items (see below)
  • sort - the sort object used for sorting collection items (see below)

Commonly useful collection methods:

  • addItem() - adds an item to the collection
  • contains() - returns whether or not an item is in a collection
  • getItemAt() - gets an item at a particular index
  • removeItemAt() - removes an item at a particular index
  • removeAll() - removes all items from the collection
  • refresh() - applies the sort and filter to the collection
  • toArray() - returns the contents of the collection as a new Array

Commonly useful collection events:

  • CollectionEvent.COLLECTION_CHANGE (collectionChange) - dispatched when the contents of a collection changes

Learn more about Collection Events...

There are many more useful methods viewable via Adobe's LiveDocs.

The below ActionScript code demonstrates some common collection methods using.

   // create a collection
   var collection:ArrayCollection = new ArrayCollection();
   
   // create a dummy object
   var item:Object = new Object();
   
   // add an item to the collection
   collection.addItem( item );
   
   // check if an item is in a collection
   var belongs:Boolean = collection.contains( item );
   
   // get the index of an item
   var index:int = collection.getItemIndex( item );
   
   // get an item by its index
   item = collection.getItemAt( index );
   
   // remove an item by it's index
   collection.removeItemAt( index );

Collections as Data Providers

Collections are commonly used as data providers.

Collections used as data providers ensure that components are properly updated when the collection's data changes.

Learn more about using Collections as Data Providers...

If you use a raw data object, such as an Array, as a control's data provider, Flex will automatically wrap the object in a collection wrapper. However, The control does not automatically detect changes that are made directly to the underlying source object.

Collection Sorting and Filtering

Collections can provide a filtered and/or sorted view of the data that does not affect the underlying source data.

If a collection is being shared as a data provider for many components, all components will be updated to reflect filtering and sorting applied to the underlying collection.

Sorting Collections

Collection sorting is programmed using a Sort object and one or more SortField objects from the mx.collections package.

General steps for setting up collection sorting:

  1. Create a Sort object
  2. Create one or more SortField objects
  3. Set the Sort/Fields on the Collection
  4. Call the Collection's refresh() method

Below is a simple example of setting a simple sort on a collection.

   collection.sort = new Sort();
   collection.sort.fields = [ new SortField(null); ];
   collection.refresh();

Sort Fields

Sort Fields are used by a Sort object to sort the items in the collection by one or more of each item's field. A SortField object encapsulates what field to sort by and how to sort it.

So each SortField added to a sort corresponds to a field of the collection items.

For instance, a sort field could specify to sort by items by the "firstName" field case-insensitively.

   // create a case-insensitive sort field
   var sortField1:SortField = new SortField( "firstName" );
   sortField1.caseInsensitive = true;

As another example, a sort field could specify to sort the "pageCount" field, a numeric value, in descending order.

   // create a numeric, descending sort field
   var sortField2:SortField = new SortField( "pageCount" );
   sortField2.numeric = true;
   sortField2.descending = true;

Sort fields are then applied to a Sort object as the fields property (array).

   var sort:Sort = new Sort();
   sort.fields = [ sortField1, sortField2 ];

If the items in the collection are all simple objects (e.g. Strings, Numbers or Dates) then a SortField instance is created passing null for the fieldName.

   // create a sort field for simple item values (no field name)
   var sortField:SortField = new SortField( null );
   sortField1.descending = true;

To apply a sort to a collection, set it's sort property and call the refresh() method.

   collection.sort = new Sort();
   ...
   collection.refresh();

For more information and examples, see Collection Sorting...

Filtering Collections

Collection filtering is programmed by creating a filter function and providing it to the collection.

The filter function must take a single Object parameter, which corresponds to a collection item, and must return a Boolean value specifying whether to include the item in the view.

   // filter out null/empty objects from the collection
   public function excludeEmpties( item:Object ):Boolean
   {
      if( item == null || item == "" )
      {
         return false; // exclude the item
      }
      return true; // include the item
   }
   
   // set the filter function on the collection
   public function applyFilter():void
   {
      this.collection.filterFunction = excludeEmpties;
      // call refresh to update the collection's "view"
      this.collection.refresh();
   }

The ActionScript code above shows how to create a filter function, called excludeEmpties(), and set it on a collection. Note that after the function is set the collection's refresh() method is called.

Changes to a collection's sort or filter properties require a call to refresh() to take effect.

Sort and Filter Example

This example demonstrates how sorting and filtering affect the view of a collection used as a list component's data provider.

TODO: embed example (CollectionsX)

In the example, the list's collection has six elements, three of which are empty strings. When the "Filter and Sort" button is clicked a filter function and sort object are set on the collection. As a result, the contents of the collection doesn't change (it still has six items), but the component's view does change (only three items are visible and sorted).

Collection Events

Collections are ideal data providers because of the notification events they provide. When the contents of a collection change, controls using the collection as a data provider are automatically updated.

Learn more about working with Collection Events...

Related Links:

Related Docs
  • ActionScript ArrayCollection The ArrayCollection class is a robust collection class that can be more useful than a standard array.
  • Flex Collection Sorting Sorting Collections with the Sort and SortField objects.
  • Flex Data Providers Several Flex components, including all list-based controls, display data from a data provider, a collection or object that contains the data displayed by the control.
Recent Docs
Random Docs
  • Flex HTML Text Text Controls support the htmlText property.
  • Flex Embedding Assets Overview of embedding assets in Flex applications.
  • ActionScript Alerts The ActionScript Alert control can be used to create interactive dialogs easily.
  • Flex StyleSheets StyleSheets define styles for Flex components and can be defined inline or loaded at run-time.
  • ActionScript ExternalInterface ActionScript's ExternalInterface class and IExternalInterface interface allow for two-way communication between ActionScript and browser JavaScript.