Flex Tip: Changing the source of an ArrayCollection

Here is a quick tip for Flex newbies although I imagine this is something thats fairly obvious. If you want to change the complete dataset of an ArrayCollection, do not create a new ArrayCollection object pointing to the same variable(well you can, but it will kill all the databound controls that are listening to events on the ArrayCollection instance). Instead use arraycollection.source = [ ... ] to repopulate the source value with a new Array. This will broadcast a CollectionEvent with the 'kind' property of the event set to 'RESET' and keep all the controls in sync. CollectionEvents are broadcasted everytime the values in an ListCollectionView instance are changed (ArrayCollections extend ListCollectionView).

I just saw this bug on an application I was working on where the controls kept getting out of sync with the core data in the ArrayCollection and this was the culprit ! The code looked something like this:

Actionscript:
  1. [Bindable]
  2. public var dataAC:ArrayCollection;
  3.  ...
  4. private function onDataLoaded(evt:Event){
  5.    dataAC = new ArrayCollection(parseIntoArray(evt.data));
  6. }

So everytime the new data came in, databinding was destroyed. The correct solution should have looked like:

Actionscript:
  1. [Bindable]
  2. public var dataAC:ArrayCollection = new ArrayCollection;
  3.  ...
  4. private function onDataLoaded(evt:Event){
  5.    dataAC.source = parseIntoArray(evt.data);
  6. }

Hope this saves some time for someone :)

4 Comments so far

  1. [...] Link From arpitonline.com [...]

  2. [...] Flex Tip: Changing the source of an ArrayCollection [...]

  3. umair on October 13th, 2008

    Thanks,

    Very useful,

    Umair

  4. oluwaseun on August 13th, 2009

    great. thanks

Leave a reply