2012-12-12 59 views
0

最近,我被要求更改一個小型的Flash應用程序,我使用外部回調而不是使用嵌入式按鈕。AS3爲聽衆添加回調

我想這個過程自動化,並用此功能上來:

/** 
    * Add an External callback for all PUBLIC methods that listen to 'listenerType' in 'listenersHolder'. 
    * @param listenersHolder - the class that holds the listeners we want to expose. 
    * @param listenerType - a String with the name of the event type we want to replace with the external callback. 
    */ 
    public static function addCallbacksForListeners(listenersHolder:*, listenerType:String):void 
    { 
     // get the holder description 
     var description:XML = describeType(listenersHolder); 
     // go over the methods 
     for each(var methodXML:XML in description..method) 
     { 
      // go over the methods parameters 
      for each(var parameterXML:XML in methodXML..parameter) 
      { 
       // look for the requested listener type 
       var parameterType:String = [email protected]; 
       if (parameterType.indexOf(listenerType) > -1) 
       { 
        var methodName:String = [email protected]; 
        trace("Found: " + methodName); 
        // get the actual method 
        var method:Function = listenersHolder[methodName]; 
        // add the callback 
        try 
        { 
         ExternalInterface.addCallback(methodName, method); 
         trace("A new callback was added for " + methodName); 
        } 
        catch (err:Error) 
        { 
         trace("Error adding callback for " + methodName); 
         trace(err.message); 
        } 
       } 
      } 
     } 

使用此功能,我不得不聽者的功能轉變爲公共之前,加空默認參數,當然還有刪除/隱藏的視覺效果。

例如來自:

私有函數onB1Click(E:MouseEvent)方法:無效

到:

公共函數onB1Click(E:的MouseEvent = NULL): void

將此行添加到init/onAdded ToStage功能:

addCallbacksForListeners(this,「MouseEvent」);

並從舞臺上刪除按鈕或只是註釋添加它的行。

我的問題是:你能找到一個更好/更有效的方法來做到這一點? 歡迎任何反饋..

回答

3

也許你應該讓JavaScript調用不同的函數名參數的單一方法。那麼你只需要添加一個回調函數,而且你不需要公開所有這些函數。

ExternalInterface.addCallback('callback', onCallback); 

public function onCallback(res:Object) 
{ 
    var functionName:String = res.functionName; 
    this[functionName](); 
} 
+0

不錯,沒想過那個。謝謝 !! –