开发者

Pass a callback in ExternalInterface

I want to call a Javascript function from Flash, which I can do with ExternalInterface, but the Javascript function takes a callback. Is there a way to give it a Flash callback?

I've thought of something like this:

ExternalInterface.addCallback("foo", function(){...});
ExternalInterface.call("theFunction", "foo");

But that wouldn't work since theFunction would attempt to do foo(), while it should really do swfObject.foo(). The problem is the page and its Javascript are not under my control (though I can request changes if really needed开发者_Python百科).


This is closely related to the first question in the related questions section.

Along the same lines as the answer to that question, you can do:

ExternalInterface.addCallback("foo", function() { /* ... */ });    // The callback
ExternalInterface.call("theFunction(function() { swfObject.foo(); })");


You're misunderstanding the documentation, I think. callback in this instance is just a reference to a function inside Flash, not a callback to something you call.

Basically, you use .call() to call a JS function from AS; and you use .addCallback() to tell the Flash Player which AS function should be called based on the name.

On your example, theFunction would get one parameter as being 'foo', which is the name that references your anonymous AS function. Not sure why you would want to pass the function like that, but if you need, you could just call it from JavaScript with

function theFunction(callback) {
    // .. do something...
    swfObject[callback]();
}

Now, if you don't have control over the JS/HTML side, I'm not sure if you can do that. Not sure why you'd need, anyway - JS calls are synchronous, as if they were running on the same thread, meaning the Flash Player will execute the JS code and only then return to the Flash Player... you don't have to wait for execution or anything.

Also, if you really need to control the page without touching the JS/HTML side, remember you can inject entire pieces of JS code via .call - it doesn't need to be a simple function call. You can create your entire functions from inside the SWF. For example,

var js:XML = <script><![CDATA[
    // Javascript code...
]]></script>;
ExternalInterface.call(js);

Or, if you need the return data, you don't need a callback either - just do a simple call as in

// JS
function isNumberZero(__num) {
    return __num == 0;
}

// AS
trace ("Is number zero = " + ExternalInterface.call("isNumberZero", 10));

Not sure if this helps at all. If not, it'd be good to have more information on what exactly you're trying to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜