views:

52

answers:

2

I'm about to write a spec for a Flash developer to build a player control that works similar to the HTML5 <audio> tag.

One of the key points is how to add callbacks, for example, with the audio tag you would do something like:

getElementById('flashAudioPlayer').addEventListener('timeupdate', function() {
  // Do stuff
});

Is it possible to have the Flash control support this type of callback passing? Instead of static 'ExternalInterface' calls, it would rather call the passed in function object, like in the above example.

Thanks!

+2  A: 

Maybe this is doable using JS eval from the Actionscript side, but I think there's an alernative.

Have your swf call a JS proxy that then broadcasts the message to the registered listeners.

Something along these lines:

JS

var proxyDispatcher = new ProxyDispatcher();
var app = getYourSwf("myswf");
// tell your app to call the dispatch method in the proxyDispatcher object everytime theres a timeupdate
//  dispatch will receive the name of the event back, plus the "payload" data (that's up to you to define)
app.registerCallback('proxyDispatcher.dispatch','timeupdate');
// now, add "clients" here
// the idea is that proxyDispatcher registers JS functions to be called when its dispatch method is called
// so, when dispatch is called with 'timeupdate' as the event type, call all listeners for 'timeupdate'...
proxyDispatcher.addEventListener('timeupdate',function() {

});

AS

var _map:Object = {};

private function handleRegisterCallback(jsCallback:String,eventName:String):void {
    _map[eventName] = jsCallback;
}

    // when there's a timeupdate, check if you have a registered listener for it; if so, call it
private function dispatchTimeupdate():void {
    if(_map['timeupdate']) {
        // call the registered function, pass the event name and any data you need
        ExternalInterface.call(_map['timeupdate'],'timeupdate','your data here');
    }
}

This could simplified if you hardcoded more stuff, but perhaps this approach is not that complicated to implement and gives you some flexibility, and makes registering to listener easy for JS "clients" (the more involved part would be in ProxyDispatcher itself).

Hope this makes sense!

Juan Pablo Califano
A: 

Ofcourse, your still going to be implementing the solution using ExternalInterface, but there is no reason you can't tell Flash which functions to call. ExternalInterface just uses strings to call the JS functions, so you can pass those to the Flash application to tell it which ones you want it to use.

You could pass them in as Flash vars or using ExternalInterface.

Tyler Egeto