首先,我们看一下下面这两段程序,有兴趣的可以运行一下。
index.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml " layout=" absolute " creationComplete="init()" >
<mx:Script>
<![CDATA[
import mediator.IndexMediator;
import mx.controls.Alert;
public var indexMediator:IndexMediator;
public var indexMediaotrTwo:IndexMediator;
public function init(): void
{
this .indexMediator = new IndexMediator( this , "indexMediator" );
this .indexMediaotrTwo = new IndexMediator( this , "indexMediatorTwo" );
}
public function buttonThreeClickListener(): void
{
Alert.show( this .indexMediator.name);
}
public function buttonFourClickListener(): void
{
Alert.show( this .indexMediaotrTwo.name);
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button id=" buttonOne " label=" buttonOne " />
<mx:Button id=" buttonTwo " label=" buttonTwo " />
<mx:Button id=" buttonThree " label=" buttonThree " click="buttonThreeClickListener()" />
<mx:Button id=" buttonFour " label=" buttonFour " click="buttonFourClickListener()" />
</mx:VBox>
</mx:Application>
IndexMediator:
package mediator
{
import flash.events.Event;
import flash.events.MouseEvent;
import mx.controls.Alert;
public class IndexMediator
{
private var _viewComponent:index;
private var _name:String = "" ;
public function IndexMediator(uiObject:Object,aName:String)
{
this ._viewComponent = index(uiObject);
this .initializeListener();
this ._name = aName;
Alert.show( "constructor is called!" );
}
private function initializeListener(): void
{
this ._viewComponent.buttonOne.addEventListener(MouseEvent.CLICK,mouseClickListener);
this ._viewComponent.buttonTwo.addEventListener(MouseEvent.CLICK,buttonTwoClickListener);
Alert.show( "initialize method is called!" );
}
public function mouseClickListener(event:Event): void
{
// this._name = "button one";
Alert.show( this ._name);
Alert.show( "button one click listener is called!" );
}
public function buttonTwoClickListener(event:Event): void
{
// this._name = "button two";
Alert.show( this ._name);
Alert.show( "button two click listener is called!" );
}
public function get name():String
{
return this ._name;
}
}
}
分析运行结果
(1) 点击buttonOne, buttonTwo 会有两个 listener 相应。
原因:
我们生成了两个mediator ,所以对页面上的这两个组件注册了两个不同的响应程序,所以他们两个会有两个响应。
(2) 点击buttonOne, buttonTwo 他们的结果相同。
原因:
这两个button 的事件监听器是由同一个对象注册的,所以他们共享同一个对象,当 buttonOne 对 _name 属性进行修改后,由于他们共享对象,所以当我们点击 buttonTwo 的时候,对象的属性已经修改了,所以显示结果跟 buttonOne 一样。
(3) 点击buttonThree, buttonFour 的结果不一样。
原因:
他们注册的监听器不一样。
从以上三点分析出Flex 注册监听器的机制,当我们注册一个监听器的时候,实际上是包括三个部分的 :
(1) 目标组件,在上面这段程序中就是button 了。
(2) 监听函数,在上面这段程序中就是 mouseClickListener 了。
(3) 最后一个是被我们忽略的,就是“当前对象”,我们注册监听器的时候也将我们的对象作为参数传递进去了,因为方法是属于对象的,所以当事件发生的时候实际的处理函数是:object.method(event) 。