CodeBehind and DI 分离MXML中的ActionScript

阅读更多

你是否开始厌倦在 mxml 中写 代码块?
你是否有通用的业务方法,要在多个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

 



	
	
	
	
	
	
	
	
	
	
	

 

5. 要注意的几点是:

  • mxml的父类是LoginPage.as
  • mxml中几个组件的id名字,要对应LoginPage.as中的 set xxx 方法
  • LoginPage.as中的组件(TextInput, Button)在被Flex加载之前都是null

 

6. 主程序如下

 


	
	
	
	
	
 

运行看看效果吧。这样就分离了表现层的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

 

  • src.zip (2.6 KB)
  • 下载次数: 45

你可能感兴趣的:(ActionScript,Flex,Adobe,CSS,PHP)