flex 学习总结
《Flex 3 权威指南》要点整理
Posted by chenchao | Filed under RIA相关
一年前整理的文档,整理文档的时候发现了,先分享出来
1.应用程序layout属性设置为absolute,才可以使用绝对定位。
2.<mx:Addchild>标签,需要指定relativeTo和position属性,relativeTo属性表示组件会添加到哪个容器。position属性表示组件会被添加到容器中的何处。
3.<mx:Model>标签允许建立客户端数据模型。
<mx:Model id=”groceryInventory”>
<groceryInventory>
<catName>Dairy</catName>
<description>Direct from California where cows are happiest</description>
</groceryInventory>
</mx:Model>
可直接使用groceryInventory.description。
4.<mx:Spacer width="100%" />
5.一般来说,当一个组件已经实例化并已正确地位于应用程序中时,会分发creationComplete事件;Flex并非从上到下创建组件,而可以看成是从里向外创建。
6.事件处理函数的命名方式clickHandler()或者doClick()。
7.HTTPService组件提供了访问URL的途径,并能从这些URL中返回数据,需要执行如下步骤:(1)创建一个HTTPService对象(2)调用对象中的send()方法(3)使用返回的数据。
使用返回的数据有两种方式:第一种直接在绑定中使用数据;第二种使用result事件处理函数
第一种:<mx:HTTPService id=”prodByCatRPC" url="http://www.flexgrocer.com/categorizedProducts.xml" />
直接使用prodByCatRPC.lastResult.allUnits.unit;
8.如果想要将数据填入控件或者正以过滤、排序等手段操作数据,则ArrayCollection才是应该选择的数据结构;对于Tree控件,使用XMLListCollection
<mx:HTTPService id="prodByCatRPC" url="http://www.flexgrocer.com/categorizedProducts.xml" resultFormat="e4x" />
<mx:XMLListCollection id="foodColl" source="{prodByCatRPC.lastResult.category}" />
<mx:Tree id="productTree" height="100%" dataProvider="{foodColl}" labelField="@name" change="populateForm(event)" />
9.ComboBox控件的dataProvider属性可以被设置为某个ArrayCollection。使用数据提供者的控件的labelFiled属性指定了dataProvider中的哪一个字段会显示给终端用户。
10.向ArrayCollection添加一组数据
var catObj:Object = new Object();
catObj.name = "All";
catObj.categoryID = 0;
categories.addItemAt(catObj, 0); // categories是ArrayCollection对象
11.当使用E4X表达式时,不需在语句中包含根结点。
12.creationComplete="unitRPC.send();prodByCatRPC.send()"
13.groceryInventory = new ArrayCollection(prodArray); // prodArray是Array对象
14.要在ArrayCollection中使用光标定位,必须先排序集合。
cursor = aItems.createCursor(); // aItems是ArrayCollection对象
sortItems(); // 排序集合
var found:Boolean = cursor.findFirst(item);
if (found)
{
var sci:ShoppingCartItem = cursor.current as ShoppingCartItem;
}
else return null;
return sci;
15.添加命名空间xmlns:="views.dataEntry.*"。
16.标签必须要有一个根结点,根结点的名称并不重要。
17.有时候需要创建UIComponent的轻量级组件,如数据管理器,HTTPService。
18.调用父级的函数this.parentDocument.categorizedProductDataLoaded(aCats);
19.itemRenderer的使用:
<mx:HorizontalList http://www.adobe.com/2006/mxml"
dataProvider="{cats}" itemRenderer="views.ecomm.TextAndPic"
horizontalScrollPolicy="off">
20.Repeater可遍历数据集,使你能访问其中的每一项。currentItem属性引用了所有数据中当前处理的部分;getRepeaterItem()方法可以返回dataProvider属性中的一项数据。
<mx:Repeater id=”myRepeater" dataProvider="{dp}">
<mx:RadioButton label={myRepeater.currentItem.name}"
click="priceLable.text = event.target.getRepeaterItem().cost" />
myButtons[0].label = "New Banana";
21.为了访问应用程序的顶级属性和方法,可以使用mx.core.Application类中的application属性。该属性提供了对Application对象的引用,在Flex应用程序的任何地方都可以使用。但不推荐。mx.core.Application.application.addToCart(prod);
22.可以利用事件流的冒泡在上层组件截获消息,这样就不需要层层传递。
23.createChildren()和updateDisplayList()方法的使用:
protected override function createChildren():void
{
super.createChildren();
btStateUp = new Button();
btStateDown = new Button();
rawChildren.addChild(btStateUp);
rawChildren.addChild(btStateDown);
}
protected override function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if (unscaledWidth > 0) this.visible = true;
else this.visible = false;
btStateUp.setActualSize(btStateUp.getExplicitOrMeasuredWidth(), btStateUp.getExplicitOrMeasuredHeight());
btStateDown.setActualSize(btStateDown.getExplicitOrMeasuredWidth(), btStateDown.getExplicitOrMeasuredHeight());
var pixelsFromTop:int = 5;
var pixelsFromRight:int = 10;
var buttonWidth:int = btStateUp.width;
var x:Number = unscaledWidth – buttonWidth – pixelsFromRight;
var y:Number = pixelsFromTop;
btStateDown.move(x, y);
btStateUp.move(x, y);
}
24.startData.selectedDate = new Date(2006, 3, 1); Flex中的月份是从0开始的,所以0代表1月,11代表12月。
25.DataGrid组件
<mx:DataGrid editable="true" draggableColumns="false" variableRowHeight="true"> // variableRowHeight设为true可使用Flex为适应缩略图而自动调整行高
<mx:DataGridColumn dataField="product" headerText="Product"
itemRenderer="renderer.ecomm.ProductName" editable="false" />
<mx:DataGridColumn dataField="quantity" headerText="Quantity"
itemEditor="mx.controls.NumericStepper" editorDataField="value"
editable="true" /> // 该列的底层数据绑定到了NumericStepper控件value属性上
<mx:DataGridColumn dataField="subtotal" headerText="Amount"
labelFunction="renderPriceLabel" editable="false" />
<mx:DataGridColumn editable="false">
<mx:itemRenderer>
<mx:Component>
<mx:VBox>
<mx:Button label="Remove" click="outerDocument.removeItem(data as ShoppingCartItem)" />
……..
private function renderPriceLabel(item:ShoppingCartItem, dataField:DataGridColumn):String
{
return "$" String(item.subtotal);
}
26.AdvancedDataGrid组件
(1)专家模式:sortExpertMode = true的时候按住Ctrl排列
(2)样式设置:
public function myStyleFunc(data:Object, col:AdvancedDataGridColumn):Object
{
if (data["cost"] == .99)
{
return {color:0xff0000, fontWeight:"bold"};
}
else return null;
}
<mx:AdvancedDataGrid dataProvider="{dp}" styleFunction="myStyleFunc"
height="250">
(3)对数据进行分组:
<mx:AdvancedDataGrid height="200" creationComplete=”myGroup.refresh()”>
<mx:dataProvider>
<mx:GroupingCollection id="myGroup" source="{dp}">
<mx:Grouping>
<mx:GroupingField name="cat" />
</mx:Grouping>
</mx:GroupingCollection>
<mx:dataProvider>
</mx:AdvancedDataGrid>
(4)显示摘要数据:
<mx:AdvancedDataGrid creationComplete="myGroup.refresh()" height="200" defaultLeafIcon="{null}">
<mx:dataProvider>
<mx:GroupingCollection id="myGroup" source="{dp}">
<mx:Grouping>
<mx:GroupingField name="cat">
<mx:summaries>
<mx:SummaryRow summaryPlacement="last">
<mx:fields>
<mx:SummaryField dataField="qty" operation="SUM" label="summary" /> // SUM/MIN/MAX/AVG
</mx:fields>
</mx:SummaryRow>
</mx:summaries>
</mx:GroupingField>
</mx:Grouping>
</mx:GroupingCollection>
</mx:dataProvider>
<mx:columns>
<mx:AdvancedDataGridColumn dataField="name" />
<mx:AdvancedDataGridColumn dataField="cost" />
<mx:AdvancedDataGridColumn dataField="qty" />
<mx:AdvancedDataGridColumn dataField="summary" />
</mx:columns>
<mx:rendererProviders>
<mx:AdvancedDataGridRendererProvider dataField="summary" columnIndex="1" columnSpan="2" renderer="renderers.SummaryText" />
</mx:rendererProviders>
</mx:AdvancedDataGrid>
27.DragSource和DragManager组件
Flex有两类拖放功能组件:增强型拖放功能组件(DataGrid,PrintDataGrid,Tree,Menu,List,HorizontailList,TileList)和非增强型拖放组件。
(1)在两个DataGrid之间拖放
向拖拽初始器添加dragEnabled属性;初始化释放目标的dataProvider;向释放目标添加dropEnabled属性。
(2)在DataGrid和List之间拖放
给释放目标List添加dragDrop方法
private function doDragDrop(event:DragEvent):void
{
var dgRow:Object = new Object();
dgRow = event.dragSource.dataForFormat("items"); //与DataGrid中的数据相关联的格式总是items
targetList.dataProvider.addItem(dgRow[0].name);
event.preventDefault(); // 取消默认行为
}
如果想让用户拖动多行数据,就要把DataGrid的multipleSelection属性设为true。
(3)用不可以直接拖拽组件上实现拖放操作
<mx:Label text="Drag me" mouseDown="dragIt(myLabel, ‘My data here’, event, ‘myFormat’)"/> // 或者mouseMove
dragEnter="doDragEnter(event, ‘myFormat’)"
dragDrop="doDragDrop(event, ‘myFormat’)"/>
private function dragIt(initiator:Label, dsData:String, event:MouseEvent, format:String):void
{
var ds:DragSource = new DragSource();
ds.addData(dsData, format);
DragManager.doDrag(initiator, ds, event);
}
private function doDragEnter(event:DragEvent, format:String):void
{
if (event.dragSource.hasFormat(format))
{
DragManager.acceptDragDrop(IUIComponent(event.target));
}
}
private function doDragDrop(event:DragEvent, format:String):void
{
var myLabelData:Object = new Object();
myLabelData = event.dragSource.dataForFormat(format);
myList.dataProvider.addItem(myLabelData);
}
(4)修改拖拽过程中显示的图片
private function dragIt(initiator:Canvas, dsData:Product, event:MouseEvent, format:String):void
{
var imageProxy:Image = new Image();
imageProxy.load("assets/" groceryItem.imageName);
imageProxy.height = 80;
imageProxy.width = 80;
var ds:DragSource = new DragSource();
ds.addData(dsData, format);
DragManager.doDrag(initiator, ds, event, imageProxy);
}
28.如果某个类没有编写构造函数,ActionScript会自动创建一个。
29.通过Model和自定义Event传递参数。
private function process():void{
var o:ObjectDataEvent=new ObjectDataEvent("ccInfoReturn",checkoutInfo);
dispatchEvent(o);
}
<mx:Model id=”checkoutInfo">
<custInfo>
<billingName>{cardType.selectedItem.data}</billingName>
<billingAddress>{cardNumber.text}</billingAddress>
<billingCity>{cardExpirationMonth.selectedItem}</billingCity>
<billingDate>{cardExpirationYear.selectedItem}</billingDate>
</custInfo>
</mx:Model>
30.使用格式器CurrencyFormatter可以四舍五入小数,设置小数的精度,指定货币符号。
<mx:CurrencyFormatter id="curFormat" currencySymbol="$" precision="2" />
<mx:Label id=”price” text=”curFormat.format(groceryItem.listPrice)}" x="100" y="20" />
31.使用格式器DataFormatter用来格式化日期,默认格式是M/DD/YYYY。
32.使用验证器ZipCodeValidaor。
<mx:ZipCodeValidator id="zipV" source="{billingZip}" property="text" domain="US or Canada" />
33.使用验证器CreditCardValidator。
<mx:CreditCardValidator id="ccV" cardTypeSource="{cardType.selectedItem}" cardTypeProperty="data"
cardNumberSource="{cardNumber}" cardNumberProperty="text"/>
private var vResult:ValidationResultEvent;
private function process():void{
vResult = ccV.validate();
if (vResult.type == ValidationResultEvent.VALID) // 验证成功
{
var o:ObjectDataEvent=new ObjectDataEvent("ccInfoReturn",checkoutInfo);
dispatchEvent(o);
}
else
{
}
}
34.使用正则表达式来验证数据。
. 表示通配符;//. 转义字符;//d 表示一个数字;//d 表示一个或多个数字;//x20 表示一个空格;[A-Za-z] 表示任意长度字母的组合
var pattern:RegExp = new RegExp(".//.[Gg][Ii][Ff]");
var pattern:RegExp = new RegExp("//d //x20[A-Za-z] ");
prodModel.imageName.search(pattern) != -1
35.构建自定义验证器类(内有正则表达式)。
public class AddressValidator extends Validator
{
private var results:Array;
public function AddressValidator()
{
super();
}
override protected function doValidation(value:Object):Array
{
results = [];
results = super.doValidation(value);
if (value != null)
{
var pattern:RegExp = new RegExp("//d //x20[A-Za-z] ");
if (value.search(pattern) == -1)
{
results.push(new ValidationResult(true, null, "notAddress", "This is not a valid US address"));
}
}
return results;
}
}
<mx:AddressValidator id="addressV" required="true" source="{billingAddress}" property="text" />
36.实现历史管理
According和TabNavigator默认启用了历史管理;ViewStack默认是禁用的,设置属性historyManagementEnabled为true即可开启。
没有默认实现历史管理的组件来实现历史管理需要以下六个步骤:
(1)该组件需要实现IHistoryManagerClient接口。
(2)用HistoryManager类注册该组件。
(3)在该组件中实现loadState()方法。 // 用户单击浏览器中的前进或后退按钮时,将激活这个方法。
(4)在该组件中实现saveState()方法。
<mx:HorizontalList http://www.adobe.com/2006/mxml"
implements="mx.managers.IHistoryManagerClient"
creationComplete="registerWithHistoryManager()">
private function registerWithHistoryManager():void
{
HistoryManager.register(this);
HistoryManager.save(); // 在第一次注册组件时,必须调用save方法,并且切换状态的时候也要调用save方法。
}
public function saveState():Object
{
var state:Object = new Object();
state.selectedIndex = this.selectedIndex;
return state;
}
public function loadState(state:Object):void
{
var newIndex:int;
if (state)
{
newIndex = int(state.selectedIndex);
}
else newIndex = -1;
if (newIndex != selectedIndex) // selectedIndex是内置变量
{
selectedIndex = newIndex;
broadcastCategoryEvent();
}
}
37.实现深度链接
<mx:HorizontalList xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="initApp()">
private var browserMgr:IBrowserManager = BrowserManager.getInstance();
private function initApp():void
{
browserMgr.init(”, "Flex Grocer"); // 浏览器的标题Flex Grocer
browserMgr.addEventListener(BrowserChangeEvent.BROWSER_URL_CHANGE, parseURL);
}
private function updateURL():void // 每点击一次调用这个函数
{
var o:Object = new Object();
o.category = selectedIndex;
var s:String = URLUtil.objectToString(o);
browserMgr.setFragment(s);
setTitle();
}
private function parseURL(event:BrowserChangeEvent = null):void
{
var o:Object = URLUtil.stringToObject(browserMgr.fragment); // 将URL片段解析为一个对象
if (!cats)
{
callLater(parseURL);
return;
}
if (o.category != null)
{
selectedIndex = o.category;
setTitle();
broadcastCategoryEvent();
}
}
private function setTitle():void
{
var title:String = "Flex Grocer – " (selectedItem as Category).catName;
browserMgr.setTitle(title);
}
38.cardTyle.setStyle(“selectionColor”, 0Xea800c); // setStyle时,颜色值只能以0x为前缀。
39.SetStyle只在父视图状态期间有效的样式。
<mx:states>
<mx:State name="expanded">
<mx:SetStyle name="styleName" value="borderBox" />
<mx:SetProperty target="{add}" name="visible" value="true" />
</mx:State>
</mx:states>
40.从CSS文件创建SWF:右击CSS文件,选择Compile To SWF选项。
41.用StyleManager加载CSS的SWF
StyleManager.loadStyleDeclarations("flexGrocer.swf"); // 加载
StyleManager.unloadStyleDeclarations("flexGrocer.swf"); // 卸载
42.加载图形皮肤
(1)在MXML标签中设置皮肤
<mx:Button upSkin="@Embed(‘../assets/myFancyUpSkin.gif’)" />
(2)在CSS块中设置皮肤
<mx:Style>
Button
{
overSkin: Embed("../assets/images/myFancyOverSkin.gif");
}
</mx:Style>
(3)在ActionScript中设置皮肤
<mx:Script>
<![CDATA[
[Embed("assets/myFancyDownSkin.gif")]
var ds:Class;
function initApp()
{
myButton.setStyle("downSkin", ds);
}
]]>
</mx:Script>
43.可编程的皮肤
public class OrangeOval extends ProgrammaticSkin // skins.OrangeOval
{
protected override function updateDisplayList(w:Number, h:Number):void
{
var lineThickness:int = 4;
var backgroundFillColor:Number;
switch (name)
{
case "upSkin":
backgroundFillColor = 0xEA800C;
break;
case "overSkin":
backgroundFillColor = 0xF8B872;
break;
case "downSkin":
backgroundFillColor = 0xB06109;
break;
case "disabledSkin":
backgroundFillColor = 0xCCCCCC;
break;
}
graphics.clear();
graphics.beginFill(backgroundFillColor);
graphics.drawEllipse(0, 0, w, h);
graphics.endFill();
}
}
.homePageButton
{
upSkin:ClassReference(‘skins.OrangeOval’);
downSkin:ClassReference(‘skins.OrangeOval’);
overSkin:ClassReference(‘skins.OrangeOval’);
disabledSkin:ClassReference(‘skins.OrangeOval’);
color: #ffffff;
}
44.使用web服务
<mx:WebService
id="dashboardWS"
wsdl="http://localhost:8300/flexGrocer/cfcs/aggregate.cfc?wsdl"
fault="showFault(event)">
<mx:operation name="getTypeSalesData" result="typeRPCResult(event)"> // getTypeSalesData函数接收2个参数,startDate和endDate
<mx:request>
<startDate>{startDate.selectedDate}</startDate>
<endDate>{endDate.selectedDate}</endDate>
</mx:request>
</mx:operation>
<mx:operation name="getSalesData" result="salesRPCResult(event)">
<mx:request>
<startDate>{startDate.selectedDate}</startDate>
<endDate>{endDate.selectedDate}</endDate>
<category>{selectedType}</category>
</mx:request>
</mx:operation>
</mx:WebService>
45.上传文件
private function fileBrowse():void
{
this.fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, selectHandler); // 该事件在用户在对话框中选中文件且单击OK按钮之后触发
fileRef.addEventListener(Event.COMPLETE, completeHandler);
var gifFilter:FileFilter = new FileFilter("GIF Images", "*.gif", "GIFF");
fileRef.browse([gifFilter]);
}
private function selectHandler(event:Event):void
{
var request:URLRequest = new URLRequest("C:/Users/chenchao/Documents/Flex Builder 3/FlexGrocer");
fileRef.upload(request);
}
private function completeHandler(event:Event):void
{
dispatchEvent(new Event("uploadComplete"));
}
46.把ActionScript对象映射到服务器对象
[RemoteClass(alias="FlexGrocer.cfcs.OrderInfo")]
public class OrderInfo
private function onResultEvent(event:ResultEvent):void
{
remoteVO = event.result as OrderInfo; // where our OrderInfo class will be populated
}
将ActionScript类绑定到Java类。
待传输类的服务器和客户端样本必须包含相同数量的属性;每个类的相同属性必须拥有相同的名字。
47.可视化数据:饼状图、柱形图和折线图
<mx:LineChart id="chart" dataProvider="{dp}" height="100%" width="100%" showDataTips="true" dataTipFunction="renderTips">
<mx:horizontalAxis> //水平轴
<mx:CategoryAxis categoryField="date" id="catAxis" />
</mx:horizontalAxis>
<mx:series>
<mx:LineSeries yField="{grossOrNet}">
</mx:LineSeries>
</mx:series>
</mx:LineChart>
<mx:Legend direction="horizontal" dataProvider="{chart}" /> //向图标添加图例
<mx:ColumnChart id="chart" dataProvider="{dp}" width="100%" height="100%">
<mx:horizontalAxisRenderers> // 限制轴上显示的标识数量
<mx:AxisRenderer canDropLabels="true" axis="{hCatAxis}" />
</mx:horizontalAxisRenderers>
<mx:horizontalAxis>
<mx:CategoryAxis id="hCatAxis" categoryField="date"/>
</mx:horizontalAxis>
<mx:verticalAxis>
<mx:LinearAxis id="vLinAxis" labelFunction="renderDollars"/>
</mx:verticalAxis>
<mx:series>
<mx:ColumnSeries yField="gross" displayName="Gross">
</mx:ColumnSeries>
<mx:ColumnSeries yField="net" displayName="Net">
</mx:ColumnSeries>
</mx:series>
</mx:ColumnChart>
<mx:SeriesInterpolate id="interpolate" elementOffset="5" /> // SeriesInterpolate 效果与 showDataEffect 效果触发器一同使用
<mx:PieChart id="chart" width="100%" height="100%" dataProvider="{dp}"
showDataTips="true" dataTipFunction="renderTips"
itemClick="broadcastTypeChange(event.hitData.item)">
<mx:series>
<mx:PieSeries field="{grossOrNet}"
labelPosition="insideWithCallout" labelFunction="renderLabel" showDataEffect="interpolate">
<mx:fills> // 用样式自定义图标外观
<mx:RadialGradient>
<mx:entries>
<mx:GradientEntry color="#EF7651" ratio="0" />
<mx:GradientEntry color="#994C34" ratio="1" />
</mx:entries>
</mx:RadialGradient>
<mx:RadialGradient>
<mx:entries>
<mx:GradientEntry color="#E9C836" ratio="0" />
<mx:GradientEntry color="#AA9127" ratio="1" />
</mx:entries>
</mx:RadialGradient>
<mx:RadialGradient>
<mx:entries>
<mx:GradientEntry color="#6FB35F" ratio="0" />
<mx:GradientEntry color="#497B54" ratio="1" />
</mx:entries>
</mx:RadialGradient>
<mx:RadialGradient>
<mx:entries>
<mx:GradientEntry color="#A1AECF" ratio="0" />
<mx:GradientEntry color="#47447A" ratio="1" />
</mx:entries>
</mx:RadialGradient>
<mx:RadialGradient>
<mx:entries>
<mx:GradientEntry color="#996666" ratio="0" />
<mx:GradientEntry color="#999966" ratio="1" />
</mx:entries>
</mx:RadialGradient>
<mx:RadialGradient>
<mx:entries>
<mx:GradientEntry color="#339933" ratio="0" />
<mx:GradientEntry color="#339999" ratio="1" />
</mx:entries>
</mx:RadialGradient>
</mx:fills>
</mx:PieSeries>
</mx:series>
</mx:PieChart>
48.本地化 Flex Application
var myResources:ResourceBundle;
myResources = new ResourceBundle("en_US", "myResources");
myResources.content["OPEN"] = "Open";
myResources.content["CLOSE"] = "Close";
resourceManager.addResourceBundle(myResources);
myResources = new ResourceBundle("fr_FR", "myResources");
myResources.content["OPEN"] = "Ouvrez";
myResources.content["CLOSE"] = "Fermez";
resourceManager.addResourceBundle(myResources);
resourceManager.update();
<mx:Label text="{resourceManager.getString(‘myResources’, ‘OPEN’)}" />
<mx:Label text="{resourceManager.getString(‘myResources’, ‘CLOSE’)}" />
<mx:Button label="English" click="changeLocale(‘en_US’)"/>
<mx:Button label="French" click="changeLocale(‘fr_FR’)"/>
private function changeLocale(locale:String):void
{
resourceManager.localeChain = [locale];
}
49.使用 Modules
(1).Loading a module with ModuleLoader
Project——Properties——Flex Modules——Add
private function loadChartModule():void
{
loader.url = "modules/ChartModule.swf";
loader.loadModule();
}
private function loadFormModule():void
{
loader.url = "modules/FormModule.swf";
loader.loadModule();
}
<mx:ModuleLoader id="loader" width="100%" height="100%" />
(2).Passing data to module
private function readyHandler(event:Event):void
{
if (loader.child is FormModule)
{
loader.child.addEventListener("submit", submitHandler);
}
}
private function submitHandler(event:ChartDataEvent):void
{
chartData = event.data;
loadChartModule();
}
<mx:ModuleLoader id="loader" width="100%" height="100%" ready="readyHandler(event)"/>
50.Managing Data on the Client
(1).Filtering data with the ArrayCollection class 过滤
[Bindable]
private var contacts:ArrayCollection;
private function filterByCity(item:Object):Boolean
{
if (item.city == filterInput.text) return true;
else return false;
}
private function doFilter():void
{
if (filterInput.text.length == 0)
{
contacts.filterFunction = null;
}
else
{
contacts.filterFunction = filterByCity;
}
contacts.refresh();
}
<mx:Button label="Filter" click="doFilter()"/>
(2).Sorting data with the ArrayCollection class 排序
[Bindable]
private var contacts:ArrayCollection;
private function doSort():void
{
var mySort:Sort = new Sort();
if (sortGroup.selectedValue.toString() == "city")
{
var field:SortField = new SortField("city", true);
mySort.fields = [field];
}
else
{
var field1:SortField = new SortField("lastname", true);
var field2:SortField = new SortField("firstname", true);
mySort.fields = [field1, field2];
}
contacts.sort = mySort;
contacts.refresh();
}
<mx:RadioButtonGroup id="sortGroup" itemClick="doSort()"/>
(3).Finding data with the IViewCursor interface 查询
private function doFind():void
{
var cursor:IViewCursor = contacts.createCursor();
var searchObj:Object = new Object();
searchObj.lastname = lnameInput.text;
searchObj.firstname = fnameInput.text;
if (cursor.findAny(searchObj))
{
myGrid.selectedItem = cursor.current;
myGrid.scrollToIndex(myGrid.selectedIndex); // 跳转到所查询到的那一行
}
}
51.TextEvent事件很好用,可以带一个字符串参数
52.调整Flash CS3中的帧率为24,因为Flex中是24帧每秒。
53.E4X expressions for parsing data
XML being searched:
<?xml version="1.0"?>
<invoices>
<invoice>
<customer>
<firstname>Maria</firstname>
<lastname>Smith</lastname>
</customer>
<items>
<lineitem price="21.41" quantity="4">Widget</lineitem>
<lineitem price="2.11" quantity="14">Mouse</lineitem>
<lineitem price="8.88" quantity="3">Wrench</lineitem>
</items>
</invoice>
<invoice>
<customer>
<firstname>John</firstname>
<lastname>Jones</lastname>
</customer>
<items>
<lineitem price="7.41" quantity="84">Mouse</lineitem>
<lineitem price="0.91" quantity="184">Mousepad</lineitem>
</items>
</invoice>
</invoices>
Select an E4X expression:
xInvoices.invoice
xInvoices.invoice[1]
xInvoices.invoice[0].customer
xInvoices..customer
xInvoices..customer.(lastname==’Jones’)
xInvoices..lineitem.(toString()==’Mouse’)
xInvoices..lineitem.(@price <
54.E4X expressions for modifying data 修改 xml 数据
xInvoices.invoice[0].customer.city=’Seattle’ // 增加city结点
xInvoices.invoice[0].items.lineitem[0].@inStock=true // 增加inStock属性
delete xInvoices.invoice[1] // 删除一个结点
delete xInvoices.invoice[0].items.lineitem // 删除一个结点
delete xInvoices.invoice[0].items.lineitem[0].@quantity // 删除一个结点中的属性
55.<mx:SWFLoader source="@Embed(‘assets/Sub2.swf’)"/>
<mx:SWFLoader source="assets/Sub2.swf"/>
56.设置组件的标签索引<mx:TextInput tabIndex="3"/>
57.Text组件
<mx:Text condenseWhite="true">
<mx:htmlText>
<![CDATA[
<font color="#ff0000"><b>the quick</b></font>
]]>
</mx:htmlText>
</mx:Text>
58.TextInput的restrict
<mx:TextInput restrict="A-Z a-z" />