Client-side data filtering with E4X and XMLListCollection

来源:互联网 发布:淘宝上的小米手环2 编辑:程序博客网 时间:2024/05/22 07:41

Suppose you're browsing a online catalog of mobile phones. You wantto see only those handsets that are of a particular brand and fallwithin a specific price range.

In other words, name == $name && price >= $minPrice && price <= $maxPrice

[screenshot]

This was easy to build in traditional web applications, where thefiltering 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 FilteredDataProviderwhose purpose was to filter a data set on a given field. I seem to havemisplaced the source for it, but never mind, it's no longer required inFlex 2.0. Data filtering is now trivial with ActionScript 3's new E4Xsupport 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}" />