2010-10-29 74 views
0

我想初始化所有狀態,如c4.currentState='down',以便我可以調用字典鍵來執行該功能,有可能嗎?動作字典包含功能

private var keyMap:Dictionary = new Dictionary(); 
private var c4v1:Object = new Object(); 
private var c4v0:Object = new Object(); 


private function initial_keyEvent():void { 
    keyMap[c4v1] = "c4.currentState='down'"; 

} 

private function call_keys():void { 
    keyMap[c4v1]; 
} 

回答

1

試試函數作爲字典的值。事情是這樣的:

private var keyMap:Dictionary = new Dictionary(); 
private var c4v1:Object = new Object(); 
private var c4v0:Object = new Object(); 

public function changeC4State():void{ 
    c4.currentState='down'; 
} 

private function initial_keyEvent():void { 
    keyMap[c4v1] = changeC4State; 
} 

private function call_keys():void { 
    var myFunc : Function = keyMap[c4v1]; 
    myFunc(); 
} 

看看中的ArrayCollection的FilterFuntion屬性或列表類的labelFunction有關此部分的詳細信息。

0

Currying會幫到你! 另外,看看Command模式。

package { 
    import flash.events.TimerEvent; 
    import flash.utils.Timer; 
    import flash.utils.Dictionary; 
    import flash.display.Sprite; 

    public class Main extends Sprite { 
     private var dictionary : Dictionary; 

     public function Main() {    
      dictionary=new Dictionary(); 

      var foo1:Foo=new Foo("John"); 
      var foo2:Foo=new Foo("Jane"); 

      dictionary[0]=curry(foo1,"Hello world"); 
      dictionary[1]=curry(foo1,"My name is John"); 
      dictionary[2]=curry(foo2,"Hello King Kong"); 
      dictionary[3]=curry(foo2,"My name is Jane"); 

      var timer:Timer=new Timer(1000,1); 
      timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerComplete); 
      timer.start(); 

      function curry(foo:Foo,message:String) : Function { 
       var f : Function = function():void { 
        foo.traceIt(message); 
       }; 
       return f; 
      } 
     } 

     private function timerComplete(e : TimerEvent) : void { 
      Timer(e.target).removeEventListener(e.type, arguments.callee); 
      dictionary[0]();//John trace : Hello world 
      dictionary[1]();//John trace : My name is John 
      dictionary[2]();//Jane trace : Hello King Kong 
      dictionary[3]();//Jane trace : My name is Jane 

     } 
    } 
} 

class Foo { 
    private var name : String; 

    public function Foo(name:String) { 
     this.name = name; 
    } 

    public function traceIt(message:String):void{ 
     trace(name,"trace :",message); 
    } 


} 
+0

可以解釋更多你的代碼將如何與Switch語句交流? – Proyb2 2010-10-30 14:30:18

+0

我的解決方案與switch語句無關...我錯過了什麼...? – OXMO456 2010-10-30 16:56:53