Suppose you're browsing a online catalog of mobile phones. You want to see only those handsets that are of a particular brand and fall within a specific price range.
In other words, name == $name && price >= $minPrice && price <= $maxPrice
This was easy to build in traditional web applications, where the filtering happened on the server side. The advantage of RIAs, though, is that a lot of such operations can be done purely on the client side, thus avoiding unnecessary server trips.
Last year I wrote a class called FilteredDataProvider whose purpose was to filter a data set on a given field. I seem to have misplaced the source for it, but never mind, it's no longer required in Flex 2.0. Data filtering is now trivial with ActionScript 3's new E4X support combined with Flex's XMLListCollection.
To use this feature on data returned from an HTTPService
, first set the service object's resultFormat
to e4x
.
<mx:HTTPService id="catalogService"url="data/catalog.xml"
resultFormat="e4x" />
Next, create an XMLListCollection
bound to the service. Also specify a filterFunction
for the collection.
<mx:XMLListCollection id="xlc"
source="{catalogService.lastResult.*}"
filterFunction="filterProduct" />
<mx:Script>
<![CDATA[
private function filterProduct(item:Object):Boolean
{
return item.name.match(new RegExp("^" + brandText.text, "i"))
&& item.price >= priceSlider.values[0]
&& item.price <= priceSlider.values[1];
}
]]>
</mx:Script>
The filterProduct
function above is called for every item in the xlc
collection. It returns true
if the item passes its test; otherwise the item is filtered out.
Finally, here's an example of a DataGrid
binding to the collection.
<mx:DataGrid dataProvider="{xlc}" />