2010-12-13 29 views
3

我做了許多的ExternalInterface調用JavaScript方法,並有這樣做的一個輔助功能:展開的... args數組在函數調用

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

然而,這意味着JavaScript的方法只能傳遞一個參數 - 參數數組 - 意味着我必須改變JavaScript來適應這個,例如而不是:

function example(argument1, argument2) 
{ 

} 

我結束了:

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

我很想做的是展開傳遞給JSCall方法的參數數組,這樣每個參數單獨傳遞給ExternalInterface調用,使得:

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

的作品,如:

ExternalInterface.call('example', 'one', 'two') 

回答

2

嘿卡梅隆,你有沒有嘗試過使用Function.apply()?試試這個:

ExternalInterface.call.apply(methodName, args); 

這太瘋狂了,它可能會工作!

+1

這確實有效,它的巧妙破解,我自己已經使用了好幾次,看起來很奇怪,90%的人第一次看到它時不明白,但嘿,太棒了! – 2010-12-13 19:24:14

+0

嗨Mims/Ivo,不幸的是,雖然這不會導致任何編譯/運行時Flash錯誤,但在嘗試執行EI調用時會引發JavaScript錯誤。 @Ivo - 你有使用這種技術的真實例子嗎? – 2010-12-15 11:01:30

+0

通過查看apply()的API文檔,我可以看到以下是如何工作的:'ExternalInterface.call.apply(null,[methodname,args])',但這與直接使用ExternalInterface.call相同, t幫助;) – 2010-12-15 11:03:16

0

在JavaScript中,這個Function.call.apply(foo, [that, test, bla])就像foo.call(that, test, bla)一樣工作,但由於ExternalInterface.call不等於Function.prototype.call,所以我們需要在這裏使用不同的方法。

// Let's fake ExternalInterface 
var funcs = { 
    example: function(arg1, arg2) { 
     console.log(arg1, arg2); 
    } 
}; 

var ExternalInterface = {}; 
ExternalInterface.call = function() { 
    var f = funcs[arguments[0]]; 
    f.call.apply(f, arguments); 
} 


// This does crazy stuff. 
function JSCall(func, args) { 
    args.unshift(func); 
    ExternalInterface.call.apply(ExternalInterface, args); 
} 

// These do the same now 
ExternalInterface.call('example', 'one', 'two'); // one two 
JSCall('example', ['one', 'two']); // one two 

注意:我沒有在ActionScript中對此進行測試。

3

撥叫多參數快速的JavaScript函數,所有你需要做的是:

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

如果你從另一個函數的參數變量列表取的參數,那麼你可以使用:

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); 
} 

別的地方,你會打電話:

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

... WH ich會在你的firebug/webkit控制檯上打印類似Testing 123 true Object的東西。

這是經過測試和確定的,因爲我在真實的項目中使用它。