获得从动态的HTTPService异步数据来填充一个先进的数据网格的Flex [英] Get data from dynamic HTTPService Asynchronous to populate an Advanced Data Grid Flex

查看:312
本文介绍了获得从动态的HTTPService异步数据来填充一个先进的数据网格的Flex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要填充的高级数据网格具有以下字段: Continent->述明─>社会 - >实际值 - >价值评估 我想模拟的金融市场,所以我必须通过异步请求从将HTTPService改变一些值;你有什么想法的话? 谢谢。 如果需要的话我会发布的。至于文件,但它是由Flex Builder中自动生成的。

I have to populate an Advanced Data Grid which have the following fields: Continent->State->Society-->Actual Value-->Estimate Value I want to simulate a financial market so i have to change some of the values by asynchronous request from an HTTPService; have you got any idea to do so? Thank you. If necessary i'll post the .as file, but it is generated automatically by Flex Builder.

下面是客户端的Flex / AIR应用程序的code:

Here's the code of the client side Flex/Air application:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"     
pageTitle="prova" 
  creationComplete="initApp()" backgroundGradientColors="[#ffffff, #ffffff]">

<mx:ViewStack id="applicationScreens" width="100%" height="100%">
    <mx:Canvas id="view" width="100%" height="100%">

    <mx:AdvancedDataGrid id="dataGrid" initialize="gc.refresh();"
        borderColor="#000000"
        selectionMode="singleRow"
        rowCount="8"
        editable="false"
        lockedColumnCount="1"
        right="10" left="10" top="10" bottom="71" itemClick="adg_itemClick(event);">
        <mx:dataProvider>
     <mx:GroupingCollection id="gc" source="{dataArr}">
         <mx:grouping>
             <mx:Grouping>
                 <mx:GroupingField name="continenteCol">
            <mx:summaries>     
          <mx:SummaryRow summaryPlacement="group">  

            <mx:fields>
              <mx:SummaryField dataField="actualCol" 
                 operation="SUM"/>
              <mx:SummaryField dataField="estimateCol" 
                 operation="SUM"/>

            </mx:fields>
          </mx:SummaryRow>
              </mx:summaries> 
                </mx:GroupingField>           
                 <mx:GroupingField name="statoCol">

          <mx:SummaryRow summaryPlacement="group">
            <mx:fields>
              <mx:SummaryField dataField="actualCol" 
                operation="SUM" />
              <mx:SummaryField dataField="estimateCol" 
                 operation="SUM"/>

            </mx:fields>
          </mx:SummaryRow>
        </mx:GroupingField>
             </mx:Grouping>
         </mx:grouping>
     </mx:GroupingCollection>
 </mx:dataProvider>
            <mx:columns>
                <mx:AdvancedDataGridColumn  resizable="false" headerText="continente" dataField="continenteCol" />
                <mx:AdvancedDataGridColumn headerText="stato" dataField="statoCol" />
                <mx:AdvancedDataGridColumn headerText="societa" dataField="societaCol" />
                <mx:AdvancedDataGridColumn headerText="actual" dataField="actualCol" />
                <mx:AdvancedDataGridColumn headerText="estimate" dataField="estimateCol" />
            </mx:columns>
    </mx:AdvancedDataGrid>


    <mx:Button id="btnAddNew" click="goToUpdate()" icon="@Embed('icons/AddRecord.png')" toolTip="Add Record" x="10" bottom="10"/>
    <mx:Button id="btnDelete" click="deleteItem()" icon="@Embed('icons/DeleteRecord.png')" toolTip="Delete Record" x="58" bottom="10"/>
    <mx:Label text="Search by continente" right="300" bottom="11"/>
    <mx:TextInput id="filterTxt" width="238" toolTip="Search by continente" enter="filterResults()" right="58" bottom="11"/>
    <mx:Button click="filterResults()" id="filterButton" icon="@Embed('icons/SearchRecord.png')" toolTip="Search by continente" right="10" bottom="10"/>

</mx:Canvas>

<mx:Canvas id="update" width="100%" height="100%">
    <mx:Form width="100%" height="80%" id="provaForm">
                <mx:FormItem label="Continente:" id="continente_form">
                    <mx:TextInput id="continenteCol" text=""/>
                </mx:FormItem>
                <mx:FormItem label="Stato:" id="stato_form">
                    <mx:TextInput id="statoCol" text=""/>
                </mx:FormItem>
                <mx:FormItem label="Societa:" id="societa_form">
                    <mx:TextInput id="societaCol" text=""/>
                </mx:FormItem>
                <mx:FormItem label="Actual:" id="actual_form">
                    <mx:TextInput id="actualCol" text=""/>
                </mx:FormItem>
                <mx:FormItem label="Estimate:" id="estimate_form">
                    <mx:TextInput id="estimateCol" text=""/>
                </mx:FormItem>
    </mx:Form>

    <mx:Button label="Save" id="btnSubmit" click="insertItem()" right="81" bottom="10"/>
    <mx:Button label="Cancel" id="btnCancel" click="goToView()" right="10" bottom="10"/>
</mx:Canvas>

</mx:ViewStack>

这里的。至于文件。

/ **  *定义UI逻辑和某些数据存取code ActionScript源文件。  *本文件链接到使用MX的主应用程序MXML文件:脚本标签。  *多数的该文件中的功能由在定义的事件处理称为  *在MXML。   / 。进口flash.events 的;

/** * ActionScript source file that defines the UI logic and some of the data access code. * This file is linked into the main application MXML file using the mx:Script tag. * Most of the functions in this file are called by event handlers defined in * the MXML. / import flash.events.;

进口mx.collections.ArrayCollection; 进口mx.controls.AdvancedDataGrid; 进口mx.controls.Alert; 进口mx.controls.advancedDataGridClasses.AdvancedDataGridColumn; 进口mx.events *。 进口mx.managers.CursorManager; 进口mx.rpc.AsyncToken; 进口mx.rpc.events.FaultEvent; 进口mx.rpc.events.ResultEvent; 进口mx.rpc.http.HTTPService;

import mx.collections.ArrayCollection; import mx.controls.AdvancedDataGrid; import mx.controls.Alert; import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn; import mx.events.*; import mx.managers.CursorManager; import mx.rpc.AsyncToken; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService;

//包括服务器端点网址中的常量定义 包括provaconfig.as;

//include the constant definition of the server endpoint URL include "provaconfig.as";

/ **  *网关:这是与服务器端的PHP code通信层  * / 私人VAR网关:的HTTPService =新的HTTPService();

/** * gateway : this is the communication layer with the server side php code */ private var gateway:HTTPService = new HTTPService();

/ **  *数组集合认为,我们在网格中使用的行  * / [可绑定] 公共变种dataArr:ArrayCollection的=新ArrayCollection的();

/** * the array collection holds the rows that we use in the grid */ [Bindable] public var dataArr:ArrayCollection = new ArrayCollection();

/ **  *我们通过排序列。这是在每次用户点击了更新  *格列标题。  *请参阅headerRelease =setOrder(事件);在DataGrid中实例化  * MXML文件  * / 私人VAR orderColumn:数字;

/** * column that we order by. This is updated each time the users clicks on the * grid column header. * see headerRelease="setOrder(event);" in the DataGrid instantiation in the * mxml file */ private var orderColumn:Number;

/ **  *字段的数据库表中的表  *需要解析响应到哈希  * / 私人VAR领域:对象= {'continente:字符串,stato:字符串,SOCIETA':字符串,实际:号码,估计:数};

/** * the list of fields in the database table * needed to parse the response into hashes */ private var fields:Object = { 'continente':String, 'stato':String, 'societa':String, 'actual':Number, 'estimate':Number};

/ **  *执行时,MXML完成加载。初始化休息网关。  * / 私有函数initApp():无效 {

/** * Executes when the mxml is completed loaded. Initialize the Rest Gateway. */ private function initApp():void {

/**
 * initialize the gateway
 * - this will take care off server communication and simple xml protocol.
 */
gateway.url = ENDPOINT_URL;
gateway.method = "POST";
gateway.useProxy = false;
gateway.resultFormat = "e4x";

/**
 * set the event handler which prevents editing of the primary key
 */
dataGrid.addEventListener(AdvancedDataGridEvent.ITEM_EDIT_BEGINNING, editCellHandler);

/**
 * set the event handler which triggers the update actions - everytime an 
 * edit operation is finished
 */

dataGrid.addEventListener(AdvancedDataGridEvent.ITEM_EDIT_END, editCellEnd);

gateway.addEventListener(ResultEvent.RESULT, resultHandler);
gateway.addEventListener(FaultEvent.FAULT, faultHandler);

fill();

}

/ **  *不允许主键列的编辑。  * @参数ê的DataGridEvent包含网格的行和列的详细信息  *当用户点击   / 私有函数editCellHandler(E:AdvancedDataGridEvent):无效 {     / 的*      *如果用户点击了主键列,停止编辑      * /     如果(e.dataField ==continenteCol)     {         即preventDefault();         返回;     } }

/** * Disallow editing of the primary key column. * @param e DataGridEvent contains details about the row and column of the grid * where the user clicked / private function editCellHandler(e:AdvancedDataGridEvent):void { /* * if the user clicked on the primary key column, stop editing */ if(e.dataField == "continenteCol") { e.preventDefault(); return; } }

/ **  *点击处理程序过滤器按钮。  *当设置另一个过滤器,刷新集合,并加载新数据  * / 私有函数filterResults():无效 {     填(); }

/** * Click handler for "Filter" button. * When setting another filter, refresh the collection, and load the new data */ private function filterResults():void { fill(); }

/ **  当用户完成编辑条目*事件处理程序触发  *触发更新的服务器命令  * / 私有函数editCellEnd(E:AdvancedDataGridEvent):无效 {     VAR dsRowIndex:INT = e.rowIndex;     VAR dsFieldName:字符串= e.dataField;     VAR dsColumnIndex:数= e.columnIndex;

/** * Event handler triggered when the user finishes editing an entry * triggers an "update" server command */ private function editCellEnd(e:AdvancedDataGridEvent):void { var dsRowIndex:int = e.rowIndex; var dsFieldName:String = e.dataField; var dsColumnIndex:Number = e.columnIndex;

var vo:* = dataArr[dsRowIndex];

var col:AdvancedDataGridColumn = dataGrid.columns[dsColumnIndex];
var newvalue:String = dataGrid.itemEditorInstance[col.editorDataField];

trace("a:" + dsRowIndex + ", " + dsFieldName + ", " + dsColumnIndex);

var parameters:* =
{
    "continente": vo.continenteCol,        "stato": vo.statoCol,        "societa": vo.societaCol,        "actual": vo.actualCol,        "estimate": vo.estimateCol    }

parameters[dsFieldName.substr(0,dsFieldName.length-3)] = newvalue;

/**
 * execute the server "update" command
 */
doRequest("Update", parameters, saveItemHandler);    

}

/ **  *对于更新服务器命令结果的处理程序。  *只是提醒错误,或者什么也不做,如果它是确定 - 数据已经  *在网格被更新  * / 私有函数saveItemHandler(E:对象):无效 {     如果(e.isError)     {         Alert.show(错误:+ e.data.error);     }     其他     {     }
}

/** * result handler for the "update" server command. * Just alert the error, or do nothing if it's ok - the data has already * been updated in the grid */ private function saveItemHandler(e:Object):void { if (e.isError) { Alert.show("Error: " + e.data.error); } else { }
}

/ **  * dragHeader处理程序数据网格。在执行此处理程序,当用户  *点击DataGrid中的一个标题列  *更新全局orderColumn变量,刷新TableCollection  *关于列@param事件的DataGridEvent细节  * / 私有函数setOrder(事件:AdvancedDataGridEvent):无效 {     orderColumn = event.columnIndex;     VAR西:的AdvancedDataGridColumn = dataGrid.columns [orderColumn]     !col.sortDescending = col.sortDescending;

/** * dragHeader handler for the datagrid. This handler is executed when the user * clicks on a header column in the datagrid * updates the global orderColumn variable, refreshes the TableCollection * @param event DataGridEvent details about the column */ private function setOrder(event:AdvancedDataGridEvent):void { orderColumn = event.columnIndex; var col:AdvancedDataGridColumn = dataGrid.columns[orderColumn]; col.sortDescending = !col.sortDescending;

event.preventDefault();
fill();

}

/ **  *点击处理程序的保存按钮,在添加状态  *收集在表单中的信息,并增加了一个新的对象到集合   / 私有函数insertItem():无效{     VAR参数: =     {         方法:插入,continente:continenteCol.text,stato:statoCol.text,SOCIETA:societaCol.text,实际:actualCol.text,估计:estimateCol.text};

/** * Click handler for the "Save" button in the "Add" state * collects the information in the form and adds a new object to the collection / private function insertItem():void { var parameters: = { "method": "Insert", "continente": continenteCol.text, "stato": statoCol.text, "societa": societaCol.text, "actual": actualCol.text, "estimate": estimateCol.text };

/**
 * execute the server "insert" command
 */
doRequest("Insert", parameters, insertItemHandler);

}

/ **  *结果处理程序插入电话。  *警报的错误,如果它存在,  *如果呼叫通过OK去了,返回到列表中,并刷新数据  * / 私有函数insertItemHandler(E:对象):无效 {     如果(e.isError)     {         Alert.show(错误:+ e.data.error);     }     其他     {         goToView();         填();     }
}

/** * Result handler for the insert call. * Alert the error if it exists * if the call went through ok, return to the list, and refresh the data */ private function insertItemHandler(e:Object):void { if (e.isError) { Alert.show("Error: " + e.data.error); } else { goToView(); fill(); }
}

/ **  *一般的效用函数用于刷新数据  *得到过滤和排序,然后调度一个新的服务器调用  *   / 私有函数填():无效 {     / 的*      *找到命令参数      * /     VAR说明:布尔= FALSE;     VAR orderField:字符串='';

/** * general utility function for refreshing the data * gets the filtering and ordering, then dispatches a new server call * / private function fill():void { /* * find the order parameters */ var desc:Boolean = false; var orderField:String = '';

if(!isNaN(orderColumn))
{
    var col:AdvancedDataGridColumn = dataGrid.columns[orderColumn];
    desc = col.sortDescending;
    //remove the 'Col' particle
    orderField = col.dataField.substr(0,col.dataField.length-3);
}

dataGrid.enabled = false;
CursorManager.setBusyCursor();

var parameters:* =
{
    "orderField": orderField,
    "orderDirection": (desc) ? "DESC" : "ASC", 
    "filter": filterTxt.text
}
/**
 * execute the server "select" command
 */
doRequest("FindAll", parameters, fillHandler);

}

/ **  *用于填充调用结果处理程序。  *如果它是一个错误,展示给用户,否则重新填充的ArrayCollection新数据  *   / 私有函数fillHandler(E:对象):无效 {     如果(e.isError)     {         Alert.show(错误:+ e.data.error);     }     其他     {         dataArr.removeAll();         每个(VAR行:XML在e.data.row)         {             VAR温度:的= {};             对于(VAR键:字符串中的字段)             {                 温度[键+'上校'] =行[关键];             }

/** * result handler for the fill call. * if it is an error, show it to the user, else refill the arraycollection with the new data * / private function fillHandler(e:Object):void { if (e.isError) { Alert.show("Error: " + e.data.error); } else { dataArr.removeAll(); for each(var row:XML in e.data.row) { var temp: = {}; for (var key:String in fields) { temp[key + 'Col'] = row[key]; }

        dataArr.addItem(temp);
    }

    CursorManager.removeBusyCursor();
    dataGrid.enabled = true;
}    

}

/ **  *点击处理程序列表中的删除按钮  *确认操作并启动deleteClickHandler功能  * / 私有函数deleteItem():无效{

/** * Click handler for the "delete" button in the list * confirms the action and launches the deleteClickHandler function */ private function deleteItem():void {

if (dataGrid.selectedItem)
{
    Alert.show("Are you sure you want to delete the selected record?",
    "Confirm Delete", 3, this, deleteClickHandler);
}

}

/ **  *事件处理函数的确认对话框时提出的  *删除按钮pssed $ P $。  *如果pressed按钮是肯定的,那么该产品将被删除。  * @参数对象事件  * @返回什么   / 私有函数deleteClickHandler(事件:的closeEvent):无效 {     如果(event.detail == Alert.YES)     {         VAR VO:的= dataGrid.selectedItem;

/** * Event handler function for the Confirm dialog raises when the * Delete button is pressed. * If the pressed button was Yes, then the product is deleted. * @param object event * @return nothing / private function deleteClickHandler(event:CloseEvent):void { if (event.detail == Alert.YES) { var vo: = dataGrid.selectedItem;

    var parameters:* =
    {
        "continente": vo.continenteCol
    }

    /**
     * execute the server "delete" command
     */
    doRequest("Delete", parameters, deleteHandler);

    setTimeout( function():void
    {
        dataGrid.destroyItemEditor();
    },
    1);
}

}

公共职能deleteHandler(五:*):无效 {     如果(e.isError)     {         Alert.show(错误:+ e.data.error);     }     其他     {         VAR continente:数= parseInt函数(e.data.toString(),10);         对于(VAR指数:数量= 0;指数&LT; dataArr.length;指数++)         {             如果(dataArr [指数] .continenteCol == continente)             {                 dataArr.removeItemAt(指数);                 打破;             }         }     }
}

public function deleteHandler(e:*):void { if (e.isError) { Alert.show("Error: " + e.data.error); } else { var continente:Number = parseInt(e.data.toString(), 10); for (var index:Number = 0; index < dataArr.length; index++) { if (dataArr[index].continenteCol == continente) { dataArr.removeItemAt(index); break; } } }
}

/ **  *反序列化XML响应  *处理错误情况  *  *参数ê的ResultEvent关于连接的服务器响应和细节   / 公共职能反序列化(OBJ:的,E:):的 {     VAR toret:对象= {};

/** * deserializes the xml response * handles error cases * * @param e ResultEvent the server response and details about the connection / public function deserialize(obj:, e:): { var toret:Object = {};

toret.originalEvent = e;

if (obj.data.elements("error").length() > 0)
{
    toret.isError = true;
    toret.data = obj.data;
}
else
{
    toret.isError = false;
    toret.metadata = obj.metadata;
    toret.data = obj.data;
}

return toret;

}

/ **  *为网关结果处理程序  *反序列化的结果,然后再调用真正的事件处理程序  *(设置使得在doRequest功能的请求时)  *  *参数ê的ResultEvent关于连接的服务器响应和细节   / 公共职能resultHandler(E:的ResultEvent):无效 {     VAR topass:的=反序列化(e.result,E);     e.token.handler.call(NULL,topass); }

/** * result handler for the gateway * deserializes the result, and then calls the REAL event handler * (set when making a request in the doRequest function) * * @param e ResultEvent the server response and details about the connection / public function resultHandler(e:ResultEvent):void { var topass: = deserialize(e.result, e); e.token.handler.call(null, topass); }

/ **  *故障处理此连接  *  *参数ê的FaultEvent错误对象  * / 公共职能faultHandler(E:的FaultEvent):无效 {     VAR的errorMessage:字符串=连接错误:+ e.fault.faultString;     如果(e.fault.faultDetail)     {         的errorMessage + =\ñ\ nAdditional细节:+ e.fault.faultDetail;     }     Alert.show(的errorMessage); }

/** * fault handler for this connection * * @param e FaultEvent the error object */ public function faultHandler(e:FaultEvent):void { var errorMessage:String = "Connection error: " + e.fault.faultString; if (e.fault.faultDetail) { errorMessage += "\n\nAdditional detail: " + e.fault.faultDetail; } Alert.show(errorMessage); }

/ **  *使得使用网关实例一请求到服务器  *  * @参数方法_字符串中的服务器dispathcer使用的方法名  *参数的参数对象名称值对发送后  通话结束时,*参数的回调函数调用的函数  * / 公共职能doRequest(方法_:字符串,参数:对象,回调:功能):无效 {     //添加方法的参数列表     参数['法'] =方法_;

/** * makes a request to the server using the gateway instance * * @param method_name String the method name used in the server dispathcer * @param parameters Object name value pairs for sending in post * @param callback Function function to be called when the call completes */ public function doRequest(method_name:String, parameters:Object, callback:Function):void { // add the method to the parameters list parameters['method'] = method_name;

gateway.request = parameters;

var call:AsyncToken = gateway.send();
call.request_params = gateway.request;

call.handler = callback;

}

/ **  *点击处理程序,当用户点击创建按钮  *载入更新画布。  * / 公共职能goToUpdate():无效 {     applicationScreens.selectedChild =更新; }

/** * Click handler when the user click the "Create" button * Load the "Update" canvas. */ public function goToUpdate():void { applicationScreens.selectedChild = update; }

/ **  *装入查看画布。  * / 公共职能goToView():无效 {     applicationScreens.selectedChild =图。 }

/** * Load the "View" canvas. */ public function goToView():void { applicationScreens.selectedChild = view; }

私有函数adg_itemClick(E:的ListEvent):无效 {     VAR项目:对象=的AdvancedDataGrid(e.currentTarget).selectedItem;     e.target.expandItem(项目,e.target.isItemOpen(项目),真的!);

private function adg_itemClick(e:ListEvent):void { var item:Object = AdvancedDataGrid(e.currentTarget).selectedItem; e.target.expandItem(item, !e.target.isItemOpen(item),true);

}

推荐答案

可能会更容易回答,如果我能看到整个应用程序,但这里有一个刺它,如果我明白你的问题......我不太清楚异步的重点...在一定程度上的http是异步。如果你的目标不过是什么,从一个应用程序服务器/数据库中的数据推送,那么答案是不同的,涉及到使用的BlazeDS / LCDS或这些技术,并在这些情况下,OSS克隆之一,你不使用MX: HttpService的反正。这是你的意思?

Might be easier to answer if I could see the whole app, but here's a stab at it if I understand your question...I'm not clear on the emphasis of asynchronous...to some extent, http is async. If however what you're aiming for is a data push from an app server/database then the answer is different and involves using BlazeDS/LCDS or one of the OSS clones of those technologies and in those cases, you're not using mx:HttpService anyways. Is this what you meant?

如果不是,那么很明显,你需要在你的MXML一个HttpService的定义,你会想拥有它的结果事件绑定到一个ActionScript函数,改变你的{dataArr}(数组,ArrayCollection的?)只要服务回报。如果你需要它轮询为您服务的变化,我想你也许可以做到这一点与Timer对象什么的,但我会考虑LCDS,如果这是必要的。

If not, then obviously, you'll need an HttpService defined in your MXML and you'll want to have it's result event bound to an ActionScript function that changes your {dataArr} (Array, ArrayCollection??) whenever the service returns. If you need it to "poll" your service for changes, I suppose you could maybe do that with a Timer object or something, but I'd consider LCDS if this is essential.

这篇关于获得从动态的HTTPService异步数据来填充一个先进的数据网格的Flex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆