FLEX中简单的 service 层与VIEW层分离的方法
FLEX中简单的 service 层与VIEW层分离的方法
?
?
一、service层
?
service类 继承 mx.rpc.http.mxml.HTTPService
在这个service类中实现数据请求,以及简单的逻辑处理
代码:
?
package services {import mx.collections.ArrayCollection;import mx.rpc.events.ResultEvent;import mx.rpc.http.mxml.HTTPService;import valueObjects.Product;public class ProductService extends HTTPService {[Bindable]public var products:ArrayCollection;public function ProductService(rootURL:String=null, destination:String=null) {super(rootURL, destination);this.resultFormat="e4x";this.url="http://www.flexgrocer.com/categorizedProducts.xml";addEventListener(ResultEvent.RESULT, handleProductResult);}private function handleProductResult( event:ResultEvent ):void {var productsArray:Array = new Array();var resultData:XMLList = event.result..product;for each (var p:XML in resultData) {var product:Product = Product.buildProductFromAttributes( p );productsArray.push( product );}products = new ArrayCollection( productsArray );}}}?
?
二、View层代码:
在View层直接用service层的标签
代码:
<?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" xmlns:views="views.*" xmlns:services="services.*" creationComplete="handleCreationComplete(event)"><fx:Declarations><!-- Place non-visual elements (e.g., services, value objects) here --><services:CategoryService id="categoryService"/><services:ProductService id="productService"/></fx:Declarations><fx:Script><![CDATA[import mx.events.FlexEvent;private function handleViewCartClick( event:MouseEvent ):void {bodyGroup.currentState="cartView";}private function handleCreationComplete(event:FlexEvent):void {categoryService.send();productService.send();}]]></fx:Script><s:controlBarLayout><s:BasicLayout/></s:controlBarLayout><s:controlBarContent><s:Button y="10" label="Checkout" id="btnCheckout" right="10"/><s:Button y="10" label="View Cart" id="btnCartView" right="90" click="handleViewCartClick( event )"/><s:Button label="Flex Grocer" x="5" y="5"/><s:List left="200" height="40" dataProvider="{categoryService.categories}" labelField="name"><s:layout><s:HorizontalLayout/></s:layout></s:List></s:controlBarContent><s:Label text="(c) 2009, FlexGrocer" right="10" bottom="10"/><views:ShoppingView id="bodyGroup" width="100%" height="100%"groceryInventory="{productService.products}"/></s:Application>?