Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrolling an ...args array in a function call

I'm making numerous ExternalInterface calls to JavaScript methods and have a helper function for doing so:

protected function JSCall( methodName:String, ...args ):void
{
  try
  {
    ExternalInterface.call( methodName, args );
  }
  … etc …
}

However this means the JavaScript method will only be passed one argument - the array of arguments - meaning I have to change the JavaScript to accomodate this, e.g. instead of:

function example(argument1, argument2)
{

}

I end up with:

function example(args)
{
  var argument1 = args[0];
  var argument2 = args[1];
}

What I'd love to do is unroll the arguments array being passed to the JSCall method so that each argument is passed individually to the ExternalInterface call, such that:

JSCall('example', ['one', 'two'])

works like:

ExternalInterface.call('example', 'one', 'two')
like image 233
Cameron Yule Avatar asked Nov 20 '25 20:11

Cameron Yule


1 Answers

To call a javascript function from flash with multiple arguments, all you have to do is:

ExternalInterface.call.apply(null, [functionName, arg1, arg2, ..., argn]);

If you're taking the arguments from a variable list of arguments of another function, then you can use:

function JSCall(methodName:String, ...args):void
{
    if (ExternalInterface.available){
        args.unshift(methodName);
        ExternalInterface.call.apply(null, args);
    }

    //btw, you can do the same with trace(), or any other function
    args.unshift('Calling javascript function');
    trace.apply(null, args);
}

Somewhere else you would call:

JSCall('console.log', 'Testing', 123, true, {foo:'bar'});

...which would print something like Testing 123 true Object on your firebug/webkit console.

This is tested and works for sure, as I'm using it in a real project.

like image 130
Brinca Avatar answered Nov 23 '25 08:11

Brinca