---
title: "Flex mate框架学习笔记(二)——Injectors"
author: "gzd3618"
date: "2009-08-26T15:52:30Z"
tags: []
slug: "flex-mate-injectors"
draft: false
lastmod: "2009-08-26T15:52:30Z"
id: 458019
url: "https://gzd3618.iteye.com/blog/458019"
---

injectors:依赖注入。借助mate的injectors可以简单的实现MVC。当A触发一事件，EventHandler拦截该事件后，可以去请求服务器或者调用其他的方法来完成业务逻辑，再由
injectors来通知B，这里有点像struts的“转向”。

1、自定义事件类

```xml
// ActionScript file
package mymate.event
{
	import flash.events.Event;
	
    public class MyEvent extends Event
    {
    		
    		public static const CLICK_ME2 = "click_me2";
    		//可以是任意类型包括对象。
    		public var name:String;
    		
    		public var password:String;
    		
    		public function MyEvent(type:String,bubbles:Boolean=true,cancelable:Boolean=false):void
    		{
    			super(type,bubbles,cancelable);
    		}
    }
}
```


2、分发事件

```xml

private function send2(event:MouseEvent):void
    		{
    			var e:MyEvent = new MyEvent(MyEvent.CLICK_ME2);
    			e.name = "谷正东2";
    			e.password="123456";
    			this.dispatchEvent(e);
    		}
<mx:Button label="点我" click="send2(event)"/>

```


3、EventMap

```xml
<?xml version="1.0" encoding="utf-8"?>
<EventMap xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="http://mate.asfusion.com/">
    <mx:Script>
    	<![cdata[
    		import mymate.event.myevent;
    		import mymate.view.a;
    		import mymate.business.testmobj;
    	]]>
    </mx:Script>
<EventHandlers type="{MyEvent.CLICK_ME2}">
		<MethodInvoker generator="{TestMObj}" method="say" arguments="{event}"/>
	</EventHandlers>
	<Injectors target="{A}">
		<PropertyInjector targetKey="isTruePwd" source="{TestMObj}" sourceKey="message"/>
	</Injectors>
</EventMap>
```


当触发事件后，EventHandlers 根据事件类型扑捉到该事件， 创建MethodInvoker 指定的TestMObj对象，并调用say方法。完成密码校验。
TestMObjct.as

```actionscript
package mymate.business
{
	import mymate.event.MyEvent;
	import mx.controls.Alert;
	
	public class TestMObj
	{
		public function TestMObj()
		{
		}
		[bindable]
		public var name:String;
		[bindable]
		public var message:String;
		
		public function say(event:MyEvent):void
		{
			var password:String = event.password;	
			if(password=="123456")
			{
				this.message = "您输入密码正确";
			}else
			{
				this.message = "您的密码输入有误";
			}
		}
	}
}
```



```xml

<Injectors target="{A}">
		<PropertyInjector targetKey="isTruePwd" source="{TestMObj}" sourceKey="message"/>
	</Injectors>
```


将TestMobject中的message 注入给A中的isTruePwd属性。

A.mxml

```xml
	[bindable]
			public var isTruePwd:String="";
			<mx:Label text="{isTruePwd+' ***'}"/>
```