Uncategorized
Working with the ArrayCollection in Flex 2
As soon as you start working with the data controls in flex 2 we start seeing references to the ArrayCollection class. The ArrayCollection class is basically a heavier and much smarter version of a standard array. In fact when you instantiate an ArrayCollection you can pass in an array as a constructor argument, and your ArrayCollection will use that as its initial data. The ArrayCollection class implement the IList and ICollectionView interfaces which give us guidelines for some of its functionality. Those implementing those interfaces give us the ability to filter and sort the data, as well as functions for manipulating the data.
All of that said and done there are a couple things that I had to do recently and the path was not very clear for me. The first task I needed to accomplish was to see if a particular object was in the ArrayCollection. My first draft of this code had me using a for loop and checking each of the individual contents of the data for a match. This is perfectly fine as a solution but it actually is a lot more work than is necessary. The ArrayCollection class actually has a contains() method which returns a boolean for your item. You call this method on your ArrayCollection and pass in the item you are looking for. Using this method you do not have to loop through the array just to see if your item is there. If the contains() method returns true you can use the getItemIndex(item:Object) function to find out where exactly it is if you need to. Using this technique might look like this:
var ac1:ArrayCollection = new ArrayCollection([0,1,2,3,4]);
var i:int;
if ( ac1.contains(1) ){
i = ac1.getItemIndex(1);
}
trace ( i );
The other task I needed to complete was concatenating a set of ArrayCollections into one bigger ArrayCollection. By default there is no simple way to add two ArrayCollections. Back in the day when we worked with regular arrays we had a neat function called concat() which took an array as a parameter and it just tacked in on the end. But ArrayCollections have no such beast. Well thats ok because we can actually reference the array that is the underlying object in our ArrayCollection using the source property of an array collection. What does that look like?
var ac1:ArrayCollection = new ArrayCollection([1,2,3,4]);
var ac2:ArrayCollection = new ArrayCollection(['a','b','c','d']);
ac1.source = ac1.source.concat(ac2.source);
trace(ac1.toString());
Running that will output “1,2,3,4,a,b,c,d” in the trace window of flex.
So next time you are working with Array’s and ArrayCollections in ActionScript 3 make sure you check the docs to see if there are any ways you can improve your code and make your life easier.
03 Jan 2007 Simeon

Just be aware that changing the internal array in ArrayCollection will not fire any events so if you’re are using it as a DataProvider you won’t see the changes.