2009-11-12 93 views
0

我需要從我的Responder對象返回值。現在,我有:從Flex/ActionScript 3 Responder對象返回

private function pro():int { 
    gateway.connect('http://10.0.2.2:5000/gateway'); 
    var id:int = 0; 
    function ret_pr(result:*):int { 
     return result 
    } 
    var responder:Responder = new Responder(ret_pr); 
    gateway.call('sx.xj', responder); 
    return id 
} 

基本上,我需要知道如何讓ret_pr的返回值到ID或任何東西,我從該函數返回。響應者似乎吃了它。我不能在其他地方使用公共變量,因爲它會一次運行多次,所以我需要本地範圍。

回答

2

這就是我如何寫AMF服務器的連接,調用它並存儲結果值。請記住,結果不會立即可用,因此您將設置響應者在數據從服務器返回後「回覆」數據。

public function init():void 
{ 
    connection = new NetConnection(); 
    connection.connect('http://10.0.2.2:5000/gateway'); 
    setSessionID(1); 
} 
public function setSessionID(user_id:String):void 
{ 
    var amfResponder:Responder = new Responder(setSessionIDResult, onFault); 
    connection.call("ServerService.setSessionID", amfResponder , user_id); 
} 

private function setSessionIDResult(result:Object):void { 
    id = result.id; 
    // here you'd do something to notify that the data has been downloaded. I'll usually 
    // use a custom Event class that just notifies that the data is ready,but I'd store 
    // it here in the class with the AMF call to keep all my data in one place. 
} 
private function onFault(fault:Object):void { 
    trace("AMFPHP error: "+fault); 
} 

我希望能指出你在正確的方向。

0
private function pro():int { 
    gateway.connect('http://10.0.2.2:5000/gateway'); 
    var id:int = 0; 
    function ret_pr(result:*):int { 
     return result 
    } 
    var responder:Responder = new Responder(ret_pr); 
    gateway.call('sx.xj', responder); 
    return id 
} 

此代碼永遠不會讓你得到你想要的。您需要使用正確的結果函數。匿名函數responder返回值不會被周圍的函數使用。在這種情況下它將總是返回0。您正在處理異步調用,並且您的邏輯需要相應處理。

private function pro():void { 
    gateway.connect('http://10.0.2.2:5000/gateway'); 
    var responder:Responder = new Responder(handleResponse); 
    gateway.call('sx.xj', responder); 
} 

private function handleResponse(result:*):void 
{ 
    var event:MyCustomNotificationEvent = new MyCustomNotificationEvent( 
      MyCustomNotificationEvent.RESULTS_RECEIVED, result); 
    dispatchEvent(event); 
    //a listener responds to this and does work on your result 
    //or maybe here you add the result to an array, or some other 
    //mechanism 
} 

使用匿名函數/閉包的關鍵是不會給你某種僞同步行爲。