Filtering a Basic Collection in Flex

18. December 2008 18:36

There are a couple interesting things to note about Flex filtering that I have learned over the past few days.

Let's say, for example, you have something like this:

private var myColl:ArrayCollection = new ArrayCollection([
{id:1, color:"Red", shape:"Circle", size:13},
{id:2, color:"Red", shape:"Square", size:5},
{id:3, color:"Green", shape:"Triangle", size:20},
{id:4, color:"Yellow", shape:"Circle", size:10}]);



and you wanted to apply a filter.  When the filter is applied to the collection, the resulting collection after myColl.refresh() will only contain the values that were returned by the filterFunction.  Now, don't get nervous.  We haven't actually changed our ability to get to our original collection.  You can verify this by looking at the collection after your refresh() with the filter applied, then setting the collection's filter function to null and calling the refresh() again.  Although it might appear that the collection is overwritten on the first refresh, it actually isn't and you can get it at any time.  So to my above collection if I want to filter off of color and size I could do something like this:

protected function myFilter(item:Object):Boolean
{
     return item.color =="Red" && item.size >= 11;
}

Then I need to set my filter function up and call my collection refresh method.

private function onInitApp():void
{
     myColl.filterFunction = myFilter;

          //Note that you dont call a function just reference its name

     myColl.refresh();

          // When this refresh() is called, Flex is going to pass each item in the
          // collection one by one to your filter function and determine if it matches the criteria.
          // If the item matches, the function will return 'true.' Internally, flex then rebuilds your collection objects.
          // You don't have to do anything else to get the values. Neat huh?
          // If you are using a data binding, the change to the collection will trigger a CollectionEvent.COLLECTION_CHANGED event
          // and the databound item will automagically reflect the changes to the collection in your component
}

What you will get back in your collection will resemble the following:

{id:1, color:"Red", shape:"Circle", size:13}

The other values aren't "gone," they just aren't shown as objects in the collection.  Now if you look at the source of myColl, you will still see them there all cozy and warm.  

Currently rated 4.0 by 3 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments


Log in