Where is IList.addAll() in AS3/Flex?
Being used to the excellent collection apis of Java, I come to expect that of other platforms too. The Flex platform has the IList interface, which amongst other methods, has the removeAll() method. Sadly, it is missing the addAll(Collection) method, so I am left to do this instead:
coll.removeAll();
var newElements : ArrayCollection = xxx as ArrayCollection;
for each (var o : Object in newElements) {
coll.addItem(o);
}
Which sucks.
You could help me out by voting for the issue 15638 on adding addAll() method.
May 26, 2008
Tags: as3, flex Posted in: Programming, Rich Internet Applications

8 Responses
Try this
ColA = ArrayCollection
ArrB = Array
var tempArr:Array = ColA.source;
tempArr.splice(-1,0,ArrB);
ColA.refresh();
You’d be better of doing this then call additem for each item. As it will send out a property change event each time, or generating a new arraycollection.
Thanks lordy.
Oops, lordy, that didn’t work. When doing the splice, the last argument (ArrB) is added as one element of type array. Taking the length of the array afterwards shows this, even though tracing it shows something else.
I ended up with this:
var sourceArray:Array = collection.source;
toAdd.forEach(function(element:*, index:int, arr:Array) : void {
sourceArray.push(element);
});
collection.refresh();
About the events. I added myself as a CollectionEvent.COLLECTION_CHANGE listener, and I only got event on the refresh.
How about this then?
var collection:ArrayCollection = new ArrayCollection([1,2,3,4,5]);
var toAdd:ArrayCollection = new ArrayCollection([6,7,8,9,10]);
collection.source = collection.source.concat(toAdd.source);
I’d vote for anything that brought us a proper collections API, because mx.collections sure ain’t one.
I’d like a nice Set implementation, as well as a more thought-through API. In the Java collection API you can actually program to the interface types, but in Flex you have to type everything as ArrayCollection to be able to do any useful work without casting from IList to ICollectionView and back again. And how come IList is mutable, but ICollectionView is not? And why is there no Set implementation?
Yeah, Set’s are important, that’s why I mentioned them twice, oh wait, three times now.
@Roland Zwaga: Works too, thanks.
Roland’s method is the best way to achieve the “addAll” functionality using the current collections API. calling addItem() in a loop will result in firing any Bindings each iteration through the loop which could be a huge performance hit. By setting the source property of the AC and using concat, you’re modifying the underlying Array and the Bindings will only fire once you call collection.refresh();
Leave a Reply