Tuesday, March 31, 2009

Filterfunctions .

Here is a quick little post on how to use filter functions .

The primary use of filterfunctions as it implies is to filter data on a data structure such as ArrayCollection which will in turn filter the data displayed on UI controls like datagrid,combobox.

The filterfunction is called with each item in the arrayCollection as a paramter. Say you have n items in the arrayCollection, the filter function will be called n times with items 0...n passed in as a parameter. The items for which the call returns true are added to the visible list, while the rest are ignored.

Lets jump in to the sample code.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
import mx.collections.ArrayCollection;
private var dataP:ArrayCollection = new ArrayCollection(
[{type:"1", data:"Montgomery",label:"Montgomery"},
{type:"2", data:"Juneau",label:"Juneau"},
{type:"1", data:"Little Rock",label:"Little Rock"},
{type:"2",data:"test 2",label:"test 2"}]);

private function handleOptionSelect() :void {
if (selectionCombo.selectedItem.toString() == "ALL") {
dataP.filterFunction = null;
} else {
dataP.filterFunction = filterOnTypes;

private function filterOnTypes(item:Object):Boolean {
if (item.hasOwnProperty("type")) {
if (item.type == selectionCombo.selectedItem.toString()) {
return true;
return false;


<mx:ComboBox change="handleOptionSelect()" id="selectionCombo">

<mx:DataGrid dataProvider="{dataP}">
<mx:DataGridColumn dataField="type"/>
<mx:DataGridColumn dataField="data"/>

Note that the elements in the arrayCollection that do not match the filter criteria removed from the arrayCollection. You can restore the original data set by setting the filter function to null and calling the refresh method again.

Wondering how the AVM knows the original set? it just stores the original data set in the "source" attribute of the arrayCollection.

Hope it helps!

Bookmark and ShareBookmark and Share

No comments: