Data transfer between AS3 and JS with a bit asynchronization.
01 February 2011
As being more familiar with JS, we proposed a website using AS3 as View and JS as model.
To make things easier, jquery1.4 is chosen to transfer data between PHP to JS, and there is almost no problem except that the oncomplete function might be executed before loaded JS code is executed, so a execution completed flag rather than code loaded completed flag is required in this case.
Things goes well until we start testing :)
The first data packet cannot be always received! After several test, we found that the communication between JS and AS3 needs initialization at the AS3 part, and this needs time. To make the website better:
Create a data queue for data from JS to AS3
When the data is into the check function, put it into the queue and check. Make the JS executing after HTML is loaded or inserting FLASH object using JS, so the flash object can surely be found. The check function will check obj.sendToActionscript === undefined (here sendToActionscript is registered using AS3's flash.external.ExternalInterface.addCallback). However, sendToActionscript is there to send data, but flash might not be ready to accept data from JS until the second frame (the first frame is loading status), so flash should tell JS that it is ready to accept data. As a result, the function flashready to mark objFlashReady = true should be defined before the object of flash. In addition, objFlashReady as a boolean should also be checked in the previously described check function. If the check function fail for obj.sendToActionscript or objFlashReady, it should be reloaded using setTimeout, otherwise it should poll all data from the queue into AS3.
Here is another thing to consider. If for some reason, a second thread is accessing the check function to send data, it should know the first thread is sending data and just push the data into the queue. Here is a small asynchronization bug: if thread1 cleared the data queue, then thread2 push a data packet, then thread2 found thread1 is sending data and ended, then thread1 mark itself ended, then there is 1 data packet remained in the queue. This will seldomly happen and will be rescued when the next data packet is transfering.
After the data can be safely transfered into AS3, we occasionally searched whether the data can be accurately transfered for all data types. However, many people say that there should be something wrong with object, so we just believe the string is safe to be from JS to AS3.
When data is from AS3 to JS, we still uses only string, but this is not enough! Some special characters will be automatically converted and an article says the trailing space will be eliminated. Things became easy after the following convertion during transfering from AS3 to JS:
% => %25
\ => %5c
" => %22
& => %26
Add a trailing non-space character.
The above convertion is undone at the JS side.
There is generally no unexpected difficulty.