直接先上源码;
分页组件Pager.mamx
<<?xml version="1.0" encoding="utf-8"?> <mx:HBox xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="initHandler(event)" xmlns:mx="library://ns.adobe.com/flex/mx" width="100%" height="100%" verticalAlign="middle"> <!-- /** <p> <code> <control:PagingBar id="serverPagingBar1" url="USER_DATAGRID" datagrid="{userAdg}" pageSize="3" destination="userFlexServices" methodName="getUsers" height="26" width="100%" /> </code> </p> */ --> <fx:Script> <![CDATA[ import com.gwtjs.events.PagerEvent; import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.controls.DataGrid; import mx.events.FlexEvent; import mx.events.PropertyChangeEvent; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.remoting.RemoteObject; import mx.utils.ObjectProxy; import spark.events.IndexChangeEvent; private var pageProxy:ObjectProxy=new ObjectProxy(); [Bindable]//每页显示的条数 private var pageSizeBoxListData:ArrayCollection = new ArrayCollection([ {pageSize:10}, {pageSize:20}, {pageSize:30}, {pageSize:50}, {pageSize:100} ]); [Bindable]//每页显示的记录数 public var pageSize:int = 10; [Bindable]//当前页 public var curpage:int = 1; [Bindable]//下一页到多少记录数 public var _offset:int = 1; [Bindable]//总页数 public var totalPage:int = 0; [Bindable]//总记录数 private var _allRecorders:int = 0; [Bindable]//组件宽度 public var widthTo:int; public function get pagerProxy():ObjectProxy { return pageProxy; } public function set pagerProxy(value:ObjectProxy):void { pageProxy = value; } public function get offset():int { return _offset; } public function set offset(value:int):void { _offset = value; } public function get allRecorders():int { return _allRecorders; } public function set allRecorders(value:int):void { _allRecorders = value; } /** * */ protected function progressBarClickHandler(event:MouseEvent):void { var bc:HBox = HBox(event.target); widthTo = event.localX; //progressBarEffect.target = progressBarPagerBlue; //progressBarEffect.play(); } /** * */ private function getMinimum():int { if(allRecorders < 1) { return 0; } else { return 1; } } /** * */ protected function pageFirstClickHandler(event:MouseEvent):void { curpage = getMinimum(); getBtnEnabled(); pagingRemoteObject(); } /** * 上一页 */ protected function pagePrevClickHandler(event:MouseEvent):void { var tempNum:int = getMinimum(); curpage = curpage - 1; getBtnEnabled(); pagingRemoteObject(); } /** * 跳转到指定页 */ protected function pageStepperClickHandler(event:MouseEvent):void { curpage = pageStepper.value; } /** * 下一页 */ protected function pageNextClickHandler(event:MouseEvent):void { if(curpage < totalPage) { curpage = curpage + 1; } getBtnEnabled(); pagingRemoteObject(); } /** * 最后一页 */ protected function pageLastClickHandler(event:MouseEvent):void { curpage = totalPage; getBtnEnabled(); pagingRemoteObject(); } /** * 刷新当前页 */ protected function pageRefreshClickHandler(event:MouseEvent):void { totalPage = getTotalPageNum(); pagingRemoteObject(); } /** * 初始化函数 */ protected function initHandler(event:FlexEvent):void { pagerProxy.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, changeMethod); trace("1111",offset,pageSize,_allRecorders,allRecorders); totalPage = getTotalPageNum();getBtnEnabled(); //pagingRemoteObject(); } private function changeMethod(evt:PropertyChangeEvent):void { if(evt.newValue){ //值有改变 allRecorders = Number(evt.newValue); totalPage = getTotalPageNum();getBtnEnabled(); trace("变化的属性名称:"+evt.property.toString()+"|新值:"+evt.newValue); trace("发生更改的对象(在监听对象的时候特别有用):"+evt.source+"|旧值:"+evt.oldValue); } } /** * 设置每页显示多少条记录 */ protected function pageSizeComboboxChangeHandler(event:IndexChangeEvent):void { var obj:Object = pageSizeCombobox.selectedItem; pageSize = obj.pageSize; //trace(offset,"",pageSize); } /** * 求总页面数 * //计算总页面数-->总页数=(总记录数+每页显示的记录数-1)/每页显示的记录数 * */ private function getTotalPageNum():int { //trace('getTotalPageNum',offset,pageSize,_allRecorders,allRecorders); return (_allRecorders + pageSize - 1) / pageSize; } /** * 获取总页数 */ private function getBtnEnabled():void { if(totalPage<=1)//所有按钮全灰掉 { pageFirstBtn.enabled = false; pagePrevBtn.enabled = false; pageNextBtn.enabled = false; pageLastBtn.enabled = false; refrePageBtn.enabled = false; }else if(curpage==1){ //当前在第一页 pageFirstBtn.enabled = false; pagePrevBtn.enabled = false; pageNextBtn.enabled = true; pageLastBtn.enabled = true; refrePageBtn.enabled = true; }else if(curpage<totalPage && curpage > 1){ //当前在中间页数,不在第一页也不在最后一页 pageFirstBtn.enabled = true; pagePrevBtn.enabled = true; pageNextBtn.enabled = true; pageLastBtn.enabled = true; refrePageBtn.enabled = true; }else if(curpage==totalPage){ //当前在最后一页 pageFirstBtn.enabled = true; pagePrevBtn.enabled = true; pageNextBtn.enabled = false; pageLastBtn.enabled = false; refrePageBtn.enabled = true; } /**如果有页数则刷新可用*/ if(totalPage > 0) { refrePageBtn.enabled = true; }else{ refrePageBtn.enabled = false; } } /** * 服务请求成功的处理 */ private function serviceSuccessResult(event:ResultEvent):void { var results:ArrayCollection = ArrayCollection(event.result.list); trace("共"+_allRecorders+"条记录","每页显示",results,"\n当前页",curpage); totalPage = getTotalPageNum(); pageStepper.value = curpage; getBtnEnabled(); //发事件到上级视图 this.dispatchEvent(new Event("myFunction")); } /** * 服务请求失败的处理 */ private function httpServiceFault(event:FaultEvent):void { var str:String = "客户端异常"; var index:int = -1; var faultCode:String = event.fault.faultCode.toString(); index = faultCode.indexOf("Server", 0); if(index!=-1) { str= "服务端异常"; } //trace(index,str); //客户端的faultCode以Client开头,服务器端的faultCode以Server开头 Alert.show(event.fault.toString(),faultCode); trace(event.fault.toString()); } /** * 这里不发送服务请求,而是将计算后的结果返回给调用的页面,供调用的页面发送服务请求 */ private function pagingRemoteObject():void { //var remote:RemoteObject = new RemoteObject(destination); //页面偏移量这里计划好了,java不需要计算了 offset = (curpage - 1) * pageSize; trace("pageSize",pageSize,"offset",offset); /*remote.getOperation(methodName).send(pageSize,_offset); remote.addEventListener(ResultEvent.RESULT,serviceSuccessResult); remote.addEventListener(FaultEvent.FAULT,httpServiceFault);*/ //这里调用上级的方法发请求,这里不发了. //发事件到上级视图 var pager:Object = new Object(); pager.offset = offset; pager.pageSize = pageSize; //发事件到上级视图 this.dispatchEvent(new PagerEvent("myPagerEvent",pager)); } protected function refrePageBtnClickHandler(event:MouseEvent):void { var obj:Object = pageSizeCombobox.selectedItem; pageSize = obj.pageSize; //Alert.show("每页显示,"+pageSize.toString()); curpage = pageStepper.value; getBtnEnabled(); pagingRemoteObject(); } private function pageHSliderChangeHandler(event:Event):void { curpage = pageStepper.value; getBtnEnabled(); pagingRemoteObject(); } ]]> </fx:Script> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <fx:Metadata> [Event(name="myPagerEvent",type="com.gwtjs.events.PagerEvent")] </fx:Metadata> <mx:HBox width="30%" height="100%" verticalAlign="middle"> <mx:LinkButton styleName="pageFirstBtn" id="pageFirstBtn" enabled="false" click="pageFirstClickHandler(event)" /> <mx:LinkButton styleName="pagePrevBtn" id="pagePrevBtn" enabled="false" click="pagePrevClickHandler(event)" /> <mx:LinkButton styleName="pageNextBtn" id="pageNextBtn" enabled="false" click="pageNextClickHandler(event)" /> <mx:LinkButton styleName="pageLastBtn" id="pageLastBtn" enabled="false" click="pageLastClickHandler(event)" /> <mx:HBox width="40%" height="100%" verticalAlign="middle"> <s:Label text="Page" /> <s:NumericStepper id="pageStepper" width="78" click="pageStepperClickHandler(event)" maximum="{totalPage}" minimum="{_allRecorders!=0?1:0}" value="{curpage}" /> <s:Label text=" Of " /> <s:Label id="totalPageLab" text="{totalPage}" /> </mx:HBox> </mx:HBox> <mx:HBox verticalAlign="middle"> <s:ComboBox dataProvider="{pageSizeBoxListData}" skinClass="assets.skin.ComboBoxTextInputEditSkin" selectedIndex="1" width="60" labelField="pageSize" id="pageSizeCombobox" change="pageSizeComboboxChangeHandler(event)" /> <s:Label text=" of {_allRecorders} " /> <mx:LinkButton id="refrePageBtn" click="refrePageBtnClickHandler(event)" styleName="myRrfreshBtn" /> </mx:HBox> <!-- <mx:LinkButton styleName="pageRefreshBtn" id="pageRefreshBtn" click="pageRefreshClickHandler(event)"/> --> <mx:HBox width="100%" height="100%" click="progressBarClickHandler(event)" verticalAlign="middle"> <s:HSlider width="98%" stepSize="1" dataTipPrecision="0" maximum="{totalPage}" minimum="{_allRecorders!=0?1:0}" value="{curpage}" change="pageHSliderChangeHandler(event)"/> </mx:HBox> <s:BorderContainer x="0" y="0" width="40%" height="20" borderColor="0x336699" textAlign="center" visible="false"> <s:Group id="hgimg" x="0" y="0" width="100%" height="100%" clipAndEnableScrolling="true"> <mx:HBox width="60%" height="18" styleName="progressBarPageBlue" id="progressBarPageBlue"> </mx:HBox> <mx:HBox width="96%" height="100%" paddingLeft="3" x="2" horizontalAlign="center" verticalAlign="middle"> <s:Label text="Displaying "/> <s:Label text="{pageSize*curpage - 1 - pageSize}" id="pageStartLab"/> <s:Label text="-"/> <s:Label text="{pageSize*curpage - 1}" id="pageSizeLab"/> <s:Label text="of"/> <s:Label text="{_allRecorders}" id="allRecordsLab"/> </mx:HBox> </s:Group> </s:BorderContainer> </mx:HBox>
分页组件主要负责以下任务:
1.处理按钮效果,当前第一页则第一页按钮和上页则灰掉,反之则然,等...;
2.计算分页参数,如多少页,每页显示多少条,剩下多少页...;
3.处理完参数将参数使用事件传递给主页面,供主页面调用服务时使用;
分页事件--PagerEvent.as
package com.gwtjs.events { import flash.events.Event; public class PagerEvent extends Event { private var _pager:Object; public function set item(item:Object):void{ this._pager = item; } public function get item():Object{ return this._pager; } public function PagerEvent(type:String,obj:Object, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); this._pager = obj; } } }
事件主要传递分页时的参数offset和pageSize
Test.mamx
<?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" creationComplete="initHandler(event)" width="99%" height="680" xmlns:components="com.gwtjs.components.*"> <s:layout> <s:BasicLayout/> </s:layout> <fx:Style source="assets/styles/main.css" /> <fx:Style source="assets/styles/icons.css" /> <fx:Script> <![CDATA[ import com.gwtjs.events.PagerEvent; import com.gwtjs.renderer.grid.EnableItemIFactory; import com.gwtjs.util.SimpleIndexUtil; import com.gwtjs.window.RoleEditorWindow; import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.events.CloseEvent; import mx.events.FlexEvent; import mx.managers.PopUpManager; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; [Bindable] [Embed("assets/images/user_edit.png")] private var userEditorIcon:Class; [Bindable] [Embed("assets/images/user_add.png")] private var userAddIcon:Class; [Bindable] //叶子节点 [Embed(source="assets/images/user_delete.png")] private var userDeleteIcon:Class; [Bindable] //定义渲染器 - 是否 private var enabledRender:IFactory = new EnableItemIFactory(); [Bindable] //叶子节点 [Embed(source="assets/images/arrow_refresh_small.png")] private var refreshBtnIcon:Class; [Bindable] private var indexRenderer:Class = SimpleIndexUtil; [Bindable] private var rolesArray:ArrayCollection = new ArrayCollection([ {roleId:"10",roleName:"系统管理员",status:1,roleAuths:"",rolesAuthNames:"",roleDesc:"系统管理员,可操作其它角色,具备全部权限" }, {roleId:"20",roleName:"安全管理员",status:1,roleAuths:"",rolesAuthNames:"",roleDesc:"系统管理员,可以自提漏洞工单的需求"}, {roleId:"30",roleName:"检测负责人",status:1,roleAuths:"",rolesAuthNames:"",roleDesc:"系统管理员,检测漏洞"}, {roleId:"40",roleName:"修复负责人",status:1,roleAuths:"",rolesAuthNames:"",roleDesc:"修复负责人,修复漏洞"} ]); private static var time:String = "2014-12-29 18:33:22"; import mx.formatters.DateFormatter; public function compareTime(str:String):Boolean { var myPattern1:RegExp=/-|:| /g; var dateFormatter:DateFormatter = new DateFormatter(); dateFormatter.formatString = "YYYY-MM-DD JJ:NN:SS"; var now:String= dateFormatter.format(new Date()); str = dateFormatter.format(str); str = str.replace(myPattern1,''); now = now.replace(myPattern1,''); if(Number(str)>Number(now)){return true;}else{return false;} } /** * 初始化函数 */ protected function initHandler(event:FlexEvent):void { var bool:Boolean = compareTime(time); if(bool){ RoleServicesController.getRoles(); } } /**添加角色*/ protected function roleAddClickHandler(event:MouseEvent):void { var itemEditorWindow:RoleEditorWindow = new RoleEditorWindow(); PopUpManager.addPopUp(itemEditorWindow,this,true); PopUpManager.centerPopUp(itemEditorWindow); //传值过去; itemEditorWindow.title = "新增角色条目"; itemEditorWindow.action = "Insert"; itemEditorWindow.items = rolesArray; itemEditorWindow.arrIndex = 3; } /** * 修改角色 * */ protected function roleEditorClickHandler(event:MouseEvent):void { var index:int = rolesArrayGrid.selectedIndex; var item:Object = rolesArray.getItemAt(index); var itemEditorWindow:RoleEditorWindow = new RoleEditorWindow(); PopUpManager.addPopUp(itemEditorWindow,this,true); PopUpManager.centerPopUp(itemEditorWindow); //传值过去; itemEditorWindow.title = "修改角色条目"; itemEditorWindow.action = "Update"; itemEditorWindow.items = rolesArray; itemEditorWindow.item = item; itemEditorWindow.arrIndex = 0; } /** * 删除角色 * */ protected function roleRemoveClickHandler(event:MouseEvent):void { var item:Object = rolesArrayGrid.selectedItem; Alert.show("确定要删除角色:"+item.roleName+"?","信息提示",(1|2),this,function(event:CloseEvent):void{ if(event.detail == Alert.YES){ for(var i:int=0;i<rolesArray.length;i++){ if(item.roleId==rolesArray[i].roleId){ rolesArray.removeItemAt(i); } } } }); } /** * 请求异常 * 客户端的faultCode以Client开头,服务器端的faultCode以Server开头 * */ private function httpServiceFault(event:FaultEvent):void { var str:String = "客户端异常"; var index:int = -1; var faultCode:String = event.fault.faultCode.toString(); index = faultCode.indexOf("Server", 0); if(index!=-1) { str= "服务端异常"; } //trace(index,str); //客户端的faultCode以Client开头,服务器端的faultCode以Server开头 Alert.show(event.fault.toString(),faultCode); trace(event.fault.toString()); } [Bindable] private var endpoint:String = "http://127.0.0.1:8080/buganalysis"; override protected function createChildren():void { if(ExternalInterface.available){ var pt:String = ExternalInterface.call("getEndopint"); trace("endpoint",pt,22222222222222); if(pt!=null) endpoint = pt; } super.createChildren(); } /** * 成功处理 * */ private function getRolesResultHandler(event:ResultEvent):void { rolesArray = ArrayCollection(event.result.userRoles); allRecorders = Number(event.result.allRecorders); //初始化分页中的总记录数 serverPagingBar1.pagerProxy.allRecorders = allRecorders; } [Bindable] public var offset:int=0; [Bindable] public var pageSize:int=20; [Bindable] public var allRecorders:int = 0; /** * 当分页组件中的分页按钮点击时就会触发此函数 * */ public function myPagerEventHandler(event:PagerEvent):void { var obj:Object = event.item; var bool:Boolean = compareTime(time); trace("obj.offset",obj.offset,"obj.pageSize",obj.pageSize); if(obj!=null){ offset = obj.offset; pageSize = obj.pageSize; } if(bool){ RoleServicesController.getRoles(); } } ]]> </fx:Script> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> <s:RemoteObject id="RoleServicesController" destination="RoleServicesController" fault="httpServiceFault(event)" endpoint="{endpoint}/messagebroker/amf"> <s:method name="getRoles" result="getRolesResultHandler(event)"> <s:arguments> <offset>{offset}</offset> <pageSize>{pageSize}</pageSize> </s:arguments> </s:method> </s:RemoteObject> </fx:Declarations> <mx:VBox width="100%" height="100%" verticalGap="0"> <mx:HBox width="100%" height="32" horizontalAlign="left" styleName="panelTitleBg" verticalAlign="middle" horizontalGap="0"> <mx:LinkButton icon="@Embed(source='assets/images/icons/grid.png')" color="#FFFFFF" fontWeight="bold" label="角色管理" /> </mx:HBox> <mx:VBox width="100%" height="100%" id="gridMainLayout" verticalGap="6" horizontalAlign="center" horizontalGap="6" paddingLeft="6" paddingRight="6" paddingBottom="6" paddingTop="6" > <mx:HBox width="100%" height="6" verticalAlign="middle" borderColor="#696969" backgroundColor="#E6E0E0" cornerRadius="6" visible="false" > <mx:LinkButton label="新增角色" icon="{userAddIcon}" styleName="btnWeight" click="roleAddClickHandler(event)" /> <mx:LinkButton label="修改角色" icon="{userEditorIcon}" styleName="btnWeight" click="roleEditorClickHandler(event)" /> <mx:LinkButton label="删除角色" icon="{userDeleteIcon}" styleName="btnWeight" click="roleRemoveClickHandler(event)" /> <mx:HBox width="100%" /> <mx:LinkButton label="刷新" icon="{refreshBtnIcon}" /> </mx:HBox> <mx:DataGrid id="rolesArrayGrid" headerStyleName="myHead" dataProvider="{rolesArray}" rowCount="{rolesArray.length}" textAlign="center" width="100%" height="80%" verticalGridLineColor="#CCCCCC" horizontalGridLines="true" horizontalGridLineColor="#CCCCCC"> <mx:columns> <mx:DataGridColumn headerText="序号" itemRenderer="{new ClassFactory(indexRenderer)}" width="50" /> <mx:DataGridColumn headerText="角色名称" dataField="roleName" textAlign="left" width="160" /> <mx:DataGridColumn headerText="状态" dataField="status" textAlign="center" width="80" itemRenderer="{enabledRender}" /> <mx:DataGridColumn headerText="角色权限" dataField="rolesAuthNames" textAlign="left" width="180"/> <mx:DataGridColumn headerText="角色说明" dataField="roleDesc" textAlign="left" /> </mx:columns> </mx:DataGrid> <components:Pager id="serverPagingBar1" myPagerEvent="myPagerEventHandler(event)" offset="{offset}" pageSize="{pageSize}" allRecorders="{allRecorders}" height="26" width="100%" /> </mx:VBox> </mx:VBox> </s:Application>
处理流程:
1.调用分页组件
<components:Pager id="serverPagingBar1" url="USER_DATAGRID" datagrid="{userDataGrid}" myPagerEvent="userDataGridPagerEventHandler(event)" myFunction="serverPagingBarFunctionHandler(event)" offset="{offset}" pageSize="{pageSize}" destination="userFlexServices" methodName="getUsers" height="26" width="100%" />
这里传入初始分页参数offset页偏移量,pageSize每页大小,myPagerEvent为分页处理事件,组件处理完分页参数后就分发事件,主页面可以执行此分页函数请求服务;
请求服务处理完成功后,再次将offset和pageSize传入Pager组件,但总记录数为动态变量,是请求数据后才有的,有点延迟,所以在pager组件里添加了二次处理方法;
/** * 成功处理 * */ private function getRolesResultHandler(event:ResultEvent):void { rolesArray = ArrayCollection(event.result.userRoles); allRecorders = Number(event.result.allRecorders); <strong>//初始化分页中的总记录数 <span style="color:#ff0000;">serverPagingBar1.pagerProxy.allRecorders = allRecorders;</span> </strong> }