Google analytics code

Monday, August 3, 2009

Flex: Event Listeners and Array Collections

While working with some code I ran into a situation where I needed to know when an ArrayCollection was updated. Normally an event is triggered when using addItem, but I needed to know when it was set to another ArrayCollection. It's not very obvious, but it is possible.

ArrayCollection is really a wrapper for an Array. You can access the "real" array in an ArrayCollection by using ".source". When you set the source property an event called "listChanged" is triggered. You can watch for this event and then do whatever you need.

So this

var newAC1:ArrayCollection = new ArrayCollection;
var newAC2:ArrayCollection = new ArrayCollection;
newAC1 = newAC2;


Is the same as this, but with an event trigger.

var newAC1:ArrayCollection = new ArrayCollection;
var newAC2:ArrayCollection = new ArrayCollection;

newAC1.addEventListener('listChanged', function(event:Event){trace('changed');});

newAC1.source = newAC2.source;

2 comments:

  1. I think you'd bettrer to use CollectionEvent.COLLECTION_CHANGE

    ReplyDelete
  2. COLLECTION_CHANGE only fires when you use the ArrayCollection methods like addItem. When you set the source of a ArrayCollection nothing happens. If you're adding/removing things to/from an ArrayCollection then I would say listen for COLLECTION_CHANGE.

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.