简体   繁体   中英

How to pass a reference to a JS function as an argument to an ExternalInterface call?


I want to be able to call a JavaScript function from a Flex app using ExternalInterface and pass a reference to a different JavaScript function as an argument.


Given the following JavaScript:

function foo(callback)
{
    // ... do some stuff
    callback();
}

function bar()
{
    // do some stuff that should happen after a call to foo
}

I want to call foo from my flex app using ExternalInterface and pass a reference to bar as the callback.


Really, foo is not my function (but, rather, FB.Connect.showBookmarkDialog ), which due to restrictions on Facebook iframe apps can only be called on a button click. My button, for design reasons, is in the Flex app. Fortunately, it's possible to call ExternalInterface.call("FB.Connect.showBookmarkDialog", callback) to display the bookmark dialog. But, FB.Connect.showBookmarkDialog requires a JS callback so, should I want to receive a callback (which I do), I need to pass a reference to a JS function as the single argument.

MXML:

<mx:Button click="showBookmarkDialog();" />

ActionScript:

function showBookmarkDialog() : void
{
    ExternalInterface.registerCallback(
        "onBookmarkDialogClosed", 
        onBookmarkDialogClosed
    );
    ExternalInterface.call(
        "FB.Connect.showBookmarkDialog", 
        /* ref to JS function onBookmarkDialogClosed ? */
    );
}

function onBookmarkDialogClosed(success:Boolean) : void
{
    // sweet, we made it back
}

JavaScript:

function onBookmarkDialogClosed()
{
    var success;
    // determine value of success
    getSWF().onBookmarkDialogClosed(success);
}

I have tried... 我试过......

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog", 
    "onBookmarkDialogClosed"
);

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog", 
    onBookmarkDialogClosed
);

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog",
    function() : void
    {
        ExternalInterface.call("onBookmarkDialogClosed");
    }
);

ExternalInterface.call(
    "FB.Connect.showBookmarkDialog",
    function()
    {
        this["onBookmarkDialogClosed"]();
    }
);

  1. Passing a string as the argument to an ExternalInterface call results in FB's JS basically trying to do `"onBookmarkDialogClosed"()` which, needless to say, will not work.
  2. Passing a function as the argument results in a function object on the other side (confirmable with `typeof`), but it seems to be an empty function; namely, `function Function() {}`

As always, one need only ask a question for the answer to be revealed...

ExternalInterface.call("FB.Connect.showBookmarkDialog(onBookmarkDialogClosed)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM