Monday, July 4, 2011

ArrayCollection in Flex: Part 3 - Listening to updates

In this tutorial we will learn how to manually listen to updates in an ArrayCollection.

In the previous tutorial, we have created a DataGrid that displays the data from ArrayCollection. Normally, if we were not making a Flex project, but rather write code in pure AS3, we would have to manually tell the DataGrid to update once the data we're displaying is updated. In the previous tutorial, however, we didn't have to do that, because Flex supports data binding.

If you remember, we set the DataGrid's dataProvider property to {myAC}:

<mx:DataGrid dataProvider="{myAC}" sortableColumns="false" />

Because we used the curly braces {} the component was updated automatically to represent the fresh information. Thanks to this, it is rarely needed to listen for updates manually. It is, however, possible, and sometimes required for an application.

When an ArrayCollection object is updated, it throws an CollectionEvent event, which we can listen to. This happens when a new item is added or an item is removed from the ArrayCollection, as well as when an item's position in the collection is changed. This type of event works with all collection objects, for example, XMLListCollection too.

We need to listen to the COLLECTION_CHANGE event:

myAC.addEventListener(CollectionEvent.COLLECTION_CHANGE, changeHandler);

private function changeHandler(evt:CollectionEvent) :void
{
trace('Update!');
}

As I said above, most of the time you would use data binding instead of listening to this event, that is because most of the times you would want to listen to updates in a data holder when using AS3 is when you would need the fresh data to display it to the user. And that is exactly what data binding is used for. It saves a lot of time for the developer.

But in reality, data binding actually consists of dispatching and listening to events like this. Sometimes it might be needed to listen to these events manually though, for example, you could use this method if you want to inform the user every time the data in a data holder has been updated.

That is all for today.

Thanks for reading!

Related:

ArrayCollection in Flex: Part 1 - Declaration
ArrayCollection in Flex: Part 2 - Sorting
ArrayCollection in Flex: Part 4 - Filtering the elements
ArrayCollection in Flex: Part 5 - Searching using a Cursor

No comments:

Post a Comment