Eliad Barazi
Eliad Barazi

Reputation: 25

AS3 add callbacks for listeners

lately I've been asked to change a small flash app i made to work with external callbacks instead of using the embedded buttons.

I tried to automate the process and came up with this function:

    /**
     * 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 = parameterXML.@type;
                if (parameterType.indexOf(listenerType) > -1)
                {
                    var methodName:String =  methodXML.@name;
                    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);
                    }
                }
            }
        }

before using this function I had to change the listener's function to Public, add null default parameter and of course remove/hide the visuals.

for example, from :

private function onB1Click(e:MouseEvent):void

to :

public function onB1Click(e:MouseEvent = null):void

add this line to the init/onAddedToStage function:

addCallbacksForListeners(this, "MouseEvent");

and remove the button from stage or just comment the line that adds it.

My question is: can you find a better/ more efficient way to do that ? any feedback is welcomed..

Upvotes: 0

Views: 400

Answers (1)

Johann Huang
Johann Huang

Reputation: 46

Maybe you should make the javascript to call a single method with different functionName param. Then you only need to add one callback and you don't need to make all those functions public.

ExternalInterface.addCallback('callback', onCallback);

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

Upvotes: 3

Related Questions