Tuesday, June 12, 2012

Flex 4 ArrayCollection and ArrayCollection.source

In Flex, generally speaking an ArrayCollection is a wrapper around the Array. So the source property in the ArrayCollection gives the data in an Array format. Recently I found a great use for this.

I had a requirement wherein I had to change some property in the grid dataProvider. What I did was that I looped through the dataProvider and changed the property for each object. 

for each (var item:Item in grid.dataProvider as ArrayCollection)
{
       item.propertyA = 1;
}

That's all. I would normally expect this to work fine. Only that it didn't. I put a trace statement and noticed that the item was repeating inside the loop. Thus only around half the items were changed and the other half weren't. My debugger showed me that the dataProvider was fine and there was no duplicates. Then how did they come in the code. I removed the line that changed the property, kept only the trace statement and lo and behold.. There was no duplicates anymore. This was very interesting.

Turns out that the ArrayCollection was sorting internally when I changed the property (No, I did not add any sort function to the ArrayCollection). This put me in a fix. How do I change data when it's order is dynamically changing.

ArrayCollection.source provided the answer. I changed my loop to

for (var i:int; i < grid.dataProvider.length; i++)
{
       (grid.dataProvider.source[i] as Item).propertyA = 1;
}

Done. Problem solved. Hope this helps someone.

No comments :