Friday, September 19, 2008

Code Review Vol. 7 - Automated JS Loading, Reformatting and Injecting with ActionScript 3.0

Based on my previous post I then abstracted a bit further. Instead of having the JavaScript embedded directly in the ActionScript I read it in, reformat it to fit my needs and then inject it into the page. I use the same instance for all file loadings so I don't store any of the values in class properties and I make my own asynchronous token pattern since it's pure AS3 and not Flex. I'll do a full walk through at a later date.


public class JSInjector extends EventDispatcher
{
public function JSInjector()
{}


public function loadExternalJS(url:String):void
{
readFile(url);
}


public function readFile(url:String):void
{
var ldr:ASyncTokenURLLoader = new ASyncTokenURLLoader()
ldr.ASyncToken = url
ldr.addEventListener(Event.COMPLETE , loadComplete,false,0,true);
ldr.addEventListener(IOErrorEvent.IO_ERROR, jsloadError,false,0,true);

var urlReq:URLRequest = new URLRequest(url);
ldr.load(urlReq)
}

private function loadComplete(event:Event):void
{
var e:AsynTokenEvent = new AsynTokenEvent(AsynTokenEvent.ASYNC_LOADED)
e.token = event.target.ASyncToken
dispatchEvent(e);
formatJS(event.target.data)
}

private function jsloadError(e:IOErrorEvent):void
{

}

private function formatJS(js:String):void
{
js = formatFunctionDefinitions(js);
js = formatGlobalVarDefinition(js)
js = js.split("var ").join(" ")
injectJS(js)
}

private function formatGlobalVarDefinition(js:String):String
{
var gvarSCPattern:RegExp =/var\s\w+\s?[^=](?=;\r|\n)/gixm
js = js.replace(gvarSCPattern, '$& = ""')
return js
}

private function formatFunctionDefinitions(js:String):String
{

var functionPattern:RegExp =/function[\s?](\w+)/gim
var newFunctionSource:String = js.replace(functionPattern, "$1 = function")
return newFunctionSource
}

private function injectJS(js:String):void
{
var externalJS:String = "function(){ "+js+" }";

try{
ExternalInterface.call(externalJS);
}catch(e:Error){

}
}

1 comment:

cmoore said...

Is there any source for the ASync Loader?