2012-12-12 61 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

不错,没想过那个。谢谢 !! –