你是否开始厌倦在 mxml 中写 <mx:Script></mx:Script> 代码块?
你是否有通用的业务方法,要在多个mxml中使用?
你是否想过,让mxml专门负责页面效果,而让as文件去负责业务?
下面的方法将提供一种方案
1. 创建一个工程叫asCodeBehind
2. 创建package
3. 创建一个as文件叫LoginPage.as
package cee.view { import mx.containers.Canvas; import mx.controls.Alert; import mx.controls.Button; import mx.controls.TextInput; public class LoginPage extends Canvas { private var _userNameInput : TextInput; private var _passwordInput : TextInput; private var _loginBtn : Button; public function LoginPage() { super(); } public function doLogin() : void { var message : String = " UserName : " + _userNameInput.text; message += "\n Password : " + _passwordInput.text; Alert.show(message); } public function set userNameInput(textInput : TextInput) : void { this._userNameInput = textInput; } public function set passwordInput(textInput : TextInput) : void { this._passwordInput = textInput; } public function set loginBtn(btn : Button) : void { this._loginBtn = btn; } } }
4. 创建一个mxml文件叫LoginPageView.mxml
<?xml version="1.0" encoding="utf-8"?> <LoginPage xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="cee.view.*" styleName="greenBorderCanvas" width="382" height="252"> <mx:Label x="57" y="78" text="Username"/> <mx:TextInput id="userNameInput" x="151" y="76"/> <mx:Label x="57" y="120" text="Password"/> <mx:TextInput id="passwordInput" x="151" y="118" displayAsPassword="true"/> <mx:Button id="loginBtn" x="151" y="178" label="Login" styleName="commandButtonBlue" click="doLogin()" /> <mx:Button x="246" y="178" label="Cancel" styleName="commandButtonBlue"/> </LoginPage>
5. 要注意的几点是:
6. 主程序如下
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:view="cee.view.*"> <mx:Style source="assets/style/style.css"/> <view:LoginPageView verticalCenter="0" horizontalCenter="0"/> </mx:Application>
运行看看效果吧。这样就分离了表现层的mxml和逻辑的ActionScript代码
参考
http://www.onflex.org/ted/2007/02/code-behind-in-flex-2.php
http://www.adobe.com/devnet/flex/articles/dependency_injection.html