05.21.09

ArrayCollection: Sort and Embellish

Posted in Flex, Programming at 11:05 am by Justin

Suppose for some reason you have an ArrayCollection that will contain a set of Strings that you want to have sorted. Then, you’d like to add an entry to the beginning and another at the end, but you don’t necessarily want the sort to apply.

var collection:ArrayCollection = new ArrayCollection([”a”,”z”,”m”]);
collection.sort = new Sort();
collection.refresh();
collection.source = collection.toArray();
collection.sort = null;
collection.refresh();
collection.addItemAt( “first”, 0 );
collection.addItem( “last” )

The key above is the line:

collection.source = collection.toArray();

This “locks” the sort by creating an Array in the order you want, rather than simply returning the elements sorted as you use the collection. If you don’t do this, when you remove the sort and refresh(), your collection will revert to its original order. Also be sure to call refresh() after you remove the sort or you’ll run into strange errors trying to add more items.

Leave a Comment