Search code examples
javascriptflashactionscript-3

Using code in both Actionscript3 and Javascript


Here's an interesting architectural query. I have a piece of code that needs to run on the server (under Node.js) and on the client (in a Flash 10 app written with Actionscript 3). The code is mostly fairly intricate object manipulation, it doesn't make any API calls, and works fine in both contexts.

So far the project is just a demo, so I've been happy to copy and paste the code into both places. But it might be quite interesting to move forward with this.

So how would you do it?

  • I assume there is no easy way to get the Flash SDK (has to build without an IDE) to read and do something useful with a .js file.

  • My only thought is that I could write a code-generator that takes the .js file and places it in an ActionScript wrapper.

Are there any obvious approaches that I've missed?


Just to pre-empt an obvious answer, I know about cross-platform languages like Haxe.


Solution

  • A possible way is using include in your wrapper Actionscript code. Just a quick and very simple test:

    package {
        import flash.display.Sprite;
        import flash.text.TextField;
    
        public class Main extends Sprite {
    
    
            private var _alertTxt:TextField;
    
            include "some.js"
    
            public function Main() {
                _alertTxt = new TextField();
                _alertTxt.multiline = true;
                _alertTxt.height = 400;
                _alertTxt.width = 400;
                addChild(_alertTxt);
                run();
            }
    
            public function alert(msg) {
                _alertTxt.text += msg + "\n";
            }
        }
    }
    

    some.js

    function run() {
        alert("run");
        var obj = {
            a : 'hello',
            b : 4.5,
            c : false
        };
        loop(obj);
    }
    
    function loop(obj) {
        for (var field in obj) {
            alert(obj[field]);
        }    
    }
    

    To compile from command-line (you might want to add other options):

    mxmlc -strict=false Main.as
    

    If you don't set strict to false, it won't compile because of the lack of type declarations.