JavaScript proxy for ActionScript 3

I find the syntax for calling JavaScript functions from ActionScript to be awkward at best. Consider the following JavaScript:

function handleClick(source) {
    // stuff
}
 
var Library = {
    processOrder: function(itemID, quantity) {
        // stuff
    }
}

The standard way of calling these functions is to use ExternalInterface:

ExternalInterface.call("handleClick", "mainPage");
ExternalInterface.call("Library.processOrder", 51829, 3);

I find the following syntax to be preferable:

JS.window.handleClick("mainPage");
JS.window.Library.processOrder(51829, 3);

Source code of the JS class that allows this syntax follows:

/*
 * This code written by Cory Petosky, http://petosky.net
 * This class may be used freely as long as this comment
 * remains intact in the source file.
 */
package net.petosky.utils {
 
    import flash.external.ExternalInterface;
    import flash.utils.flash_proxy;
    import flash.utils.Proxy;
 
    public dynamic class JS extends Proxy {
        private var _call:String = "";
 
        public static function get window():JavaScript {
            return new JS();
        }
 
        override flash_proxy function callProperty(name:*, ...args):* {
            args.unshift(_call + name);
            _call = "";
            return ExternalInterface.call.apply(null, args);
        }
 
        override flash_proxy function getProperty(name:*):* {
            _call += name + ".";
            return this;
        }
    }
}

Post new comment

The content of this field is kept private and will not be shown publicly.