Local Connection as2 to as3, and back
Filed under Lab Work, Programming | Tags:Actionscript 2,Actionscript 3,Flash,LocalConnection
It’s been a while because things are so crazy busy. The last few weeks has been all about papervision. 3D is totally new to me. The terminology, 3D vertices, Matrix, etc…it’s deep…literally. Anyway, today’s post is not about that. I was tasked with importing the youtube chromeless player into papervision. This meant i had to also create the player controls. However, before doing anything, i needed to get these guys to talk with each other. Getting as3 to talk to as2 was no problem. A new local connection object, set a connection ‘frequency’ (using the connect method) get’s the one way communication all set up. Going the other way (from as2 to as3) was as simple, just not as intuitive. It comes down to the following key points:
- each swf needs two local connection objects – one to send, one to receive. Both objects will have unique connection names. However, all connection names must be shared in each swf.
- the as3 swf uses a ‘client’ (a generic object or custom class) to receive the events from as2. -ie…the callback. that was the key for me
in all, here is a generic sample (source)
as2:
var lcGet:LocalConnection = new LocalConnection() lcGet.connect('as2bridge') var lcSend:LocalConnection = new LocalConnection() lcGet.command = function(method:String,args:Array) { trace('command received'+method+" "+args); var ob:Object = this ob[method].apply(this,args[0]); textbox.text = args; lcSend.send('fromAs2','callingBackToAs3','yipeeeee!') } function write(msg:String) { textbox.text = msg; } textbox.text = ' i am the as2 swf';
as3 class
package com.loomisgroup { import flash.display.*; import flash.events.*; import flash.net.*; public class AS3Bridger extends MovieClip { public var ld:Loader; public var lcGet:LocalConnection; public var lcRec:LocalConnection; public var rec:LocalConnection; public function AS3Bridger():void { lcGet = new LocalConnection() ; lcGet.addEventListener(StatusEvent.STATUS,onStatus) lcRec = new LocalConnection() lcRec.connect('fromAs2'); var myClient = new Object(); lcRec.client = myClient; myClient.callingBackToAs3 = function (e){trace(e,'is the call back from as2')}; var req:URLRequest = new URLRequest(); req.url = 'as2.swf'; ld = new Loader(); ld.contentLoaderInfo.addEventListener(Event.COMPLETE,loaded); ld.load(req); addChild(ld); } public function onStatus(e:StatusEvent):void { trace('calling back now') } public function loaded(e:Event):void { var m = this.getChildByName('mc') m.addEventListener(MouseEvent.CLICK,cl)</code> } private function cl(e:MouseEvent) { lcGet.send('as2bridge','command','write','and now it is as3'); } } }