ActionScriptでインクリメンタルサーチ
AJAX関係でよくあるインクリメンタルサーチのActionScript版.
これもArrayにあるfilterメソッドの練習として作ってみました.
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()"> <mx:ArrayCollection id="a" /> <mx:Script> <![CDATA[ private function search(event:KeyboardEvent):void{ searchResult.dataProvider = a.toArray().filter( function(item:*, index:int, arr:Array):Boolean{ var word:String = item as String; var input:String = inputForSearch.text; return word.substr(0, input.length).toLowerCase() == input.toLowerCase(); }); } private function initApp():void{ a = new ArrayCollection(["aaa", "aaabbb", "abcd", "efgh", "ef15", "EF81"]); searchResult.dataProvider = a; } ]]> </mx:Script> <mx:Panel title="インクリメンタルサーチ" width="250" height="200" layout="absolute" horizontalCenter="0" verticalCenter="0"> <mx:List width="100%" height="100%" id="searchResult"></mx:List> <mx:ControlBar> <mx:Label text="検索語を入力してください"/> <mx:TextInput width="100%" id="inputForSearch" keyUp="search(event)"/> </mx:ControlBar> </mx:Panel> </mx:Application>
TextInputからはtextinputというイベントも飛ぶのですが,これを使うと仮名漢字変換中のキーボードイベントも受け取ることになるようなので,KeyUpの方でやってみました.
この例では大文字小文字を区別しない検索になっていますが,区別したい場合はfilter部分を次のようにすれば良いです.
private function search(event:KeyboardEvent):void{ searchResult.dataProvider = a.toArray().filter( function(item:*, index:int, arr:Array):Boolean{ var word:String = item as String; var input:String = inputForSearch.text; return word.substr(0, input.length) == input; }); }