views:

730

answers:

1

From a button in Flash I just want to call a function written in jQuery.
When I place the function outside jQuery's $(document).ready it works fine:
*btw I use SWFObject to embed Flash.

AS3:

import flash.external.ExternalInterface;
function test_fnc(event:Event):void {
    ExternalInterface.call("jsFunction", "hello world");
}
test_mc.addEventListener("click", test_fnc);

JS:

<script type="text/javascript">     
    function jsFunction(words) {
        alert(words); // "hello world";
    }
    $(document).ready(function() {
        // not from here
    });
</script>
+1  A: 

At the time the Flash makes a call to jsFunction it is not defined. You have a race condition where $(document).ready is firing after the ExternalInterface call is made, so anything defined within $(document).ready would not yet have executed, and therefore be unavailable at the time Flash makes the call.

In response to your comment:

You need both Flash to be ready and the document to be ready for this to work. I'm not sure an order of initialization is guaranteed, so I'd advise you to call a known function from Flash that tells JS that it is ready. Perhaps something like this:

var waitingForItems=2;
function itemReady()
{
    //called from both Flash and $(document).ready
    --waitingForItems;
    if(waitingForItems==0)
    {
        //create your array
        //send to Flash by calling Flash rather having Flash call JS
    }
}
$(document).ready(function(){
    itemReady();
});
spender
thanks for the answer spender. At the end and saw the light.. I just defined var alt_array outside doc.ready and could than access the array from Flash. Now I still need to get it to work with IE7.
FFish