2012-04-17 6 views
0

でコールバックを使用する方法:それでは、私は次のコードを持っているとしましょうActionScriptの

public function first(text:String):String { 
    _text = text; 
    dispatchEvent(event); 

    //Want this statement to return the value of _text 
    //after handler has finished transforming text. 
    return _text; 
} 

//handles the event 
public function handler(event:Event):void { 
    //does things, then changes the value of _text 
    _text = "next text that first needs to return"; 
} 

どのように私はこの方法は(最初の)それは(ハンドラ)によって変換された後_textの正しい値を返すことを確認します?

ありがとうございます!

+0

ActionScriptは、形式 '名使用しています:引数のtype'が、ない'タイプNAME'を。 – Marty

+0

私はイベントで正しいと思いましたが、私はflexとjavaの間であまりにも多くの切り替えを行っています。これは混乱です。しかし、それを指摘していただきありがとうございます:) – user220755

+0

ええ私はこれとC#の間で同じ問題があります:P – Marty

答えて

0

ActionScriptはシングルスレッド言語であり、イベントハンドラは値を返さないため、_textがパッケージスコープ内で可変であればコードが動作すると想定しています。次のコードは、大きな意味がありませんが、あなたは別のクラスからfirst関数を呼び出す場合、それは便利です

package 
{ 
    import flash.display.Sprite; 
    import flash.events.Event; 


    public class EventTest extends Sprite 
    { 
     public function EventTest() 
     { 
      addEventListener("sliceText", sliceHandler); 

      //will be Some 
      var newText:String = first("SomeText"); 
      trace(newText); 
     } 

     private var _text:String; 

     public function first(text:String):String 
     { 
      _text = text; 

      dispatchEvent(new Event("sliceText")); 

      return _text; 
     } 

     protected function sliceHandler(event:Event):void 
     { 
      //let's slice text to be more valuable 
      _text = _text.slice(0,4); 
     } 

    } 
} 
+0

あなたがイベントをディスパッチすると、(最初の)結果を得るのを待つことはなく、単に_textの前の値を返します、 右? – user220755

+0

いいえ、私が言ったように、ActionScriptはシングルスレッド言語です。つまり、イベントをディスパッチすると、プロセスはリスナーになり、すべてのリスナーが実行を終了した後で、ディスパッチ命令の次のプロセスに移ります。したがって、私の例では、sliceHandlerはreturn文の前に起動されます。 – Art

関連する問題