mxmlを使わずにAS3だけでFlexアプリケーションを書く

全国のActionScripterの皆様こんにちは!id:holidays-lです!

今回訳あって、AS3だけでFlexアプリケーションを作れるのかを試してみました。


こんなミニマムコードを

MyApp.as

package {
    import mx.core.Application;
    public class MyApp extends Application {
    }
}


ビルドして

$ mxmlc MyApp.as


MyApp.swfを実行してみたところ

TypeError: Error #1009: null のオブジェクト参照のプロパティまたはメソッドにアクセスすることはできません。
	at mx.core::UIComponent/getStyle()
	at mx.core::UIComponent/createInFontContext()
	at mx.controls::Button/createChildren()
	at mx.core::UIComponent/initialize()
	at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::childAdded()
	at mx.core::Container/http://www.adobe.com/2006/flex/mx/internal::childAdded()
	at mx.core::Container/addChildAt()
	at mx.core::Container/addChild()
	at MyApp()
	at MyApp_mx_managers_SystemManager/create()
	at mx.managers::SystemManager/initializeTopLevelWindow()
	at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler()
	at mx.managers::SystemManager/docFrameListener()

とエラーが出てしまいました。
どうがんばっても解消できなかったので検索してみましたが、日本語で解説しているものは皆無でした(なのでこの記事書いてます)



mxmlを使わずにAS3だけでFlexアプリケーションを書くのは無理だなんてことがこのあたりのスレッドで書かれてます。
actionscript.org
(まあ実行されるべきコードを探してきてコピペしまくれば出来るのかも知れませんが、そこまでやる気ないです。)


結局メインはmxmlでないとダメだと言うことで、先ほどのリンク先では


If you'd rather build an application entirely in ActionScript, this is the minimum requirements for MXML:



where "MyActionScriptApp" is a component built in ActionScript (MyActionScriptApp.as). Easy as pie. :)

と解決策が書かれていますが、MyActionScriptAppをApplicationから派生したものにすればもっと短く出来ますよね、これ。


というわけで、AS3だけで作った最小のFlexアプリケーションはこうなります。
MyApp.mxml

<MyAppImpl xmlns="*"/>

さっき書いたMyApp.asだけどそのままだとMyApp.mxmlと名前が被るので、package名を付けるか名前変えるかしないといけないので、とりあえずMyAppImplにした。

package {
    import mx.core.Application;
    public class MyAppImpl extends Application {
    }
}

これらをビルドして

$ mxmlc MyApp.mxml

MyApp.swfを実行するとエラー無く動きます。やったね!