comboBox 的 itemMatchingFunction & labelToItemFunction

一天闲来无事,研究一下comboBox的应用,发现这两个方法,咋一看还有点不知所云,所以下定决心研究一下到底用来做啥的。

itemMatchingFunction 

就是在提示输入区输入字符用来搜索时的回调函数。它是在textInput change时候触发的,会去按顺序匹配(忽略大小写)首先找到的那一项并选中它。

但是很多时候我们需要自定义一下搜索的规则,譬如我们不想它从开头开始严格匹配,只要包含了输入的字符就显示包含输入字符最接近位置的那一项。它返回的是一个vector<int>,然后comboxBox回选中vector中第一个index。代码见下面。

  labelToItemFunction

 就是你再搜索时,如果没有搜索到匹配的值,那么就返回这个函数的返回值。所以如果你想在没有搜索到就添加一项到comboBox的数据源,就要用到这个函数了。(代码见下面)

 

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:view="com.view.*">
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.collections.ArrayList;
			
			import spark.components.ComboBox;
			import spark.events.IndexChangeEvent;
			[Bindable]
			public var complexDP:ArrayCollection = new ArrayCollection(
				[    {ingredient:"Salmon", category:"Meat"}, 
					{ingredient:"Potato", category:"Starch"}, 
					{ingredient:"Cucumber", category:"Vegetable"}, 
					{ingredient:"Steak", category:"Meat"}, 
					{ingredient:"Rice", category:"Starch"}, 
					{ingredient:"Cumin", category:"Spice"}
				]                
			);
			
			private function myLabelFunction(item:Object):String
			{
				return item ? item.name + " " + item.phone : "";
			}
			
			private function myMatchingFunction(comboBox:ComboBox, inputText:String):Vector.<int>
			{
				var vec:Vector.<int> = new Vector.<int>();
				var maxIndex:int = -1;
				var findIndex:int;
				for(var i:int; i < complexDP.length; i++)
				{
					var index:int = String(complexDP.getItemAt(i).ingredient).indexOf(inputText);
					if( index > 0)
					{
						if(maxIndex == -1 || maxIndex > index)
						{
							maxIndex = index;
							findIndex = i;
						}
					}
				}
				vec.push(findIndex);
				return vec;
			}
			
			private function myLabelToItemFunction(input:String):*
			{
				return {ingredient:input, category:"mystery"};
			}  
			
			protected function bcc_changeHandler(event:IndexChangeEvent):void
			{
				if(complexDP.getItemIndex(bcc.selectedItem) == -1)
				{
					complexDP.addItem(bcc.selectedItem);
				}
			}
		]]>
	</fx:Script>
	<s:layout>
		<s:VerticalLayout/>
	</s:layout>
	<s:ComboBox 
		id="bcc"
		dataProvider="{complexDP}" 
		itemMatchingFunction="myMatchingFunction"
		change="bcc_changeHandler(event)"
		labelToItemFunction="myLabelToItemFunction"
		width="150" 
		selectedIndex="0" 
		labelField="ingredient"/>  
</s:Application>

 

 

 

 

 

你可能感兴趣的:(Flex,combobox)