Updating item lists of Flex data controls

posted in: ActionScript 3, Flash | 0

A recent project had a requirement that the items displayed in one ComboBox changed depending on the selected value of another ComboBox. This is a fairly common occurrence; I see it quite a lot on flight booking sites where the list of destination airports changes based on the selection of departure airport.

However when I tried to update the XMLList that was attached to my ComboBox I found that the list of items was not being updated all the time. Strangely it seemed to be updated the first time I changed the contents of the XMLList but not on subsequent changes.

I have to thank Peter Cowling for his reply to my question posted to ActionScript.org, which directed me to the Adobe docs that explained that although the dataprovider property of this (and other controls) takes various data types, the data is automatically wrapped into a Collection – i.e in my case the XMLList would be wrapped into an XMLListCollection.

The ComboBox then uses the onCollectionChange event to monitor if the list has been update and automatically takes the appropriate action.

So the simple solution for me was to pass an XMLListCollection to the dataprovider, and update the XMLListCollection when required.

I must admit rather than writing the code to clear out the XMLListCollection and re-insert a new set of items one by one, I just created a new instance of an XMLListCollection based on an XMLList and let the garbage collection handle tidying up the memory allocation.

Anyway, the result is the same, and works well.

BTW. The AS3 XML processing functions are very funky
My code to update the dataprovider ended up being just one line

theDataProvider = new XMLListCollection(dataSet.gearbox.item.(@FuelType.indexOf(fuel)!=-1));