Handling Javascript in AS3

Handling Javascript calls via Actionscript 3 and ExternalInterface is cool. But in larger projects I’d like to have more controll over it. I spotted some things I didn’t like:

  1. Via addCallback(”func”, asFunc)  – You can register a function twice
  2. You can’t see how much js calls / callbacks you’ve registerd and how often the were called.

So I wrote a small Singleton class called JsHandler which can deal with that issues. You can register callBacks and do Javascript calls. Furthermore the class provides two methods which report about the calls. A basic Error Handling is implemnted too.

I know I did a nasty hack for the …rest params. But I think it’s a good Solution for the problem. Noone needs more than 6 params in a Javascript function ;)

Update:

Thanks to lab9 for the apply and unshift hint. Now you can push as much params as you want to. I updated the class. The trick is:

// function name (string)
args.unshift(jsFunctionName);
// ...args
ExternalInterface.call.apply(instance, args);

Here is the Democode:

JsHandler.addCallBack("sendToAs", fromJs);
// Second one causes error (same name)
JsHandler.addCallBack("sendToAs", fromJs);    
 
// returns the js return value as string
JsHandler.doCall("sendToJs2", "p1", "p2");
JsHandler.doCall("sendToJs2", "p1");
 
// returns array of all callbacks
JsHandler.allCallBacks();
 
// returns array with all methodnames
// and call amount
JsHandler.allCalls();

The class is just roughly tested and might contain errors. If you’ve any feedback or questions don’t hesitate to ask.

Responses (Add Your Comment)

  1. for the …rest params, the apply method can be helpful

    in your case :


    public static function doCall(jsFunctionName : String, ... args) : String
    {
    if(ExternalInterface.available)
    {
    if(args.length > MAX_PARAM_AMOUNT)
    {
    throw new Error(ERR_TO_MOUCH_PARAMS);
    return null;
    }
    else
    {
    countFunctionCall(jsFunctionName);
    args.unshift(jsFunctionName);
    ExternalInterface.call.apply(this, args);
    }
    }
    else
    {
    throw new Error(ERR_EI_NOT_AVAILABLE);
    return null;
    }
    }
    }

    and that should doit :)

  2. thanks for your reply! i will check / implement this! looks like a great solution

 

Leave a Reply

Formatting: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">