mxmlからスクリプトを分離する
開発環境:FlashDevelop 4.0.4
プロジェクト:AIR Mobile Flex App
確認端末:Xperia acro
mxmlからスクリプトを分離する方法。
mxmlはviewsフォルダ、asはscriptフォルダに入れることにした。
参考:
http://d.hatena.ne.jp/cu39/20120302/1330682460
http://blog.air-life.net/2008/03/viewmxmllogicactionscript.html
src/views/HomeView.mxml
<?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:script="script.*" actionBarVisible="false" title="HomeView"> <s:layout> <s:VerticalLayout paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" /> </s:layout> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> <script:HomeViewScript id="script" /> </fx:Declarations> <s:HGroup> <s:Label text="A: " fontSize="20" /> <s:TextInput id="inputA" text="0" width="100" /> <s:Label text=" + " fontSize="20" /> <s:Label text="B:" fontSize="20" /> <s:TextInput id="inputB" text="0" width="100" /> </s:HGroup> <s:Button id="addCalc" label="足し算" width="200" /> <s:HGroup> <s:Label text="答え:" fontSize="20" /> <s:Label id="resultValue" fontSize="70" /> </s:HGroup> </s:View>
actionBarVisible="false" をするとタイトルの表示が消せる。
src/script/HomeViewScript.as に新規作成
package script { import views.HomeView; import flash.events.MouseEvent; import mx.core.IMXMLObject; import mx.events.FlexEvent; /** * ... * @author example */ public class HomeViewScript implements IMXMLObject { private var view:HomeView; public function initialized(document:Object, id:String):void { view = HomeView(document); view.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler); } private function creationCompleteHandler(e:FlexEvent):void { //ここからコントロールに対する処理をする view.resultValue.text = "?"; view.addCalc.addEventListener(MouseEvent.CLICK, addCalc_clickHandler); } private function addCalc_clickHandler(e:MouseEvent):void { //HomeView.mxmlのコントロール(id)から値を取得する var _inputA:Number = parseFloat(view.inputA.text); var _inputB:Number = parseFloat(view.inputB.text); //足し算 var result:Number = _inputA + _inputB; //結果を返す view.resultValue.text = result.toString(); } } }
mxmlとasのファイル名を同じにしたかったけどスクリプト側で import views.HomeView; にしてても、view = HomeView(document); でエラーになった。