As we have an AS2 Journal, this is where I'll put, from time to time, something I find interesting about AS3.
Today, I'll tell you some practical things about LocalConnection. The class works in the same way for both AS3 and AS2, so it is the only thing that can connect two swf's published in different AS versions.
With it, you can call a method within an AS2 swf from an AS3 swf (and vice-versa, of course). Although LocalConnection has other uses as well (like letting swf's from different domains comunicate to each other), today I'm only discussing the practical use of making two different AS version SWF's comunicate.
Things to have in mind:
- You will always have two swf's:
1.one of them is the sending swf file (which must contain the method to be invoked and a call to the send() method)
2.the other one is the receiving swf file (which is the file that invokes the method and must contain a call to the connect() method) - Both swf's must have a LocalConnection object with the same names
Let's have a look at an example:
This is the AS3 swf (let's call it FullFlashSite_AS3.swf) inside of which we load the AS2 movie (let's call it VideoPlayer_AS2.swf). We need to be able to call the doSomething() method from within VideoPlayer_AS2
//creating the LocalConnection instance to communicate to VideoPlayer_AS2 movie
var vPlayer_LC : LocalConnection = new LocalConnection();
//loading the VideoPlayer_AS2 into our current AS3 movie
var loader:Loader = new Loader();
loader.load(new URLRequest("VideoPlayer_AS2.swf"));
addChild(loader);
//creating the event that will trigger the call to the VideoPlayer_AS2 function
loader.addEventListener(MouseEvent.CLICK, callingAS2);
function callingAS2(event:MouseEvent):void
{
// send callingAS2 event to the new connection "SiteAS3_to_PlayerAS2"
vPlayer_LC.send("SiteAS3_to_PlayerAS2", "pleaseRespond");
}
This is the AS2 swf named VideoPlayer_AS2.swf . It already has the doSomething() method defined
//creating the LocalConnection instance with the same name as the other side's
var vPlayer_LC : LocalConnection = new LocalConnection();
//telling VideoPlayer_AS2 what to do when it hears the "pleaseRespond" event handler
vPlayer_LC.pleaseRespond = function()
{
VideoPlayer_AS2.doSomething();
}
//telling VideoPlayer_AS2 to listen for calls via the "SiteAS3_to_PlayerAS2" connection
vPlayer_LC.connect("SiteAS3_to_PlayerAS2");
This is not all. With some uses of the LocalConnection you will face synchronisation issues (think of it like this: I send a call to receive a result. The other side starts computing the result, but gives me the answer before it finishes). We'll handle this in the next AS3 tip