1.     为多个组件注册一个监听器<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

你可以为相同或不同组件的任意数量的事件注册同一个监听器函数。下面的例子为两个按钮注册了同一个监听器函数:submitForm()

 

<?xml version="1.0"?>

<!-- events/OneHandlerTwoComponentsInline.mxml -->

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Script><![CDATA[

import mx.controls.Alert;

private function submitForm(e:Event):void {

// Handle event here.

Alert.show("Current Target: " + e.currentTarget.id);

}

]]></mx:Script>

<mx:Button id="b1"

label="Click Me"

click="submitForm(event)"

/>

<mx:Button id="b2"

label="Click Me, Too"

click="submitForm(event)"

/>

</mx:Application>

 

当你要使用addEventListener()方法为多个组件的事件注册同一个事件监听器的时候,需要分别为每个实例调用addEventListener()方法。如下所示:

 

<?xml version="1.0"?>

<!-- events/OneHandlerTwoComponentsAS.mxml -->

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

creationComplete="createHandlers(event)">

<mx:Script><![CDATA[

import mx.controls.Alert;

public function createHandlers(e:Event):void {

b1.addEventListener(MouseEvent.CLICK, submitForm);

b2.addEventListener(MouseEvent.CLICK, submitForm);

}

private function submitForm(e:Event):void {

// Handle event here.

Alert.show("Current Target: " + e.currentTarget.id);

}

]]></mx:Script>

<mx:Button id="b1" label="Click Me"/>

<mx:Button id="b2" label="Click Me, Too"/>

</mx:Application>

 

当做完这些之后,你可以为事件监听器添加处理事件的逻辑。事件的目标(或者是调度了事件的组件)被添加到Event对象。你可以通过Event对象的targettype属性来决定如何处理事件。

 

下面的例为按钮控件的点击事件和一个复选框控件的点击事件注册了一个监听器函数myEventHandler()。要确定是哪个对象调用了事件监听器,监听器通过在case语句中检查Event对象的targetclassName属性来做到这一点:

 

<?xml version="1.0"?>

<!-- events/ConditionalTargetHandler.mxml -->

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="initApp()">

<mx:Script><![CDATA[

import mx.controls.Alert;

public function initApp():void {

button1.addEventListener(MouseEvent.CLICK, myEventHandler);

cb1.addEventListener(MouseEvent.MOUSE_DOWN, myEventHandler);

}

public function myEventHandler(event:Event):void {

switch (event.currentTarget.className) {

case "Button":

// Process Button click.

Alert.show("You clicked the Button control.");

break;

case "CheckBox":

// Process CheckBox click.

Alert.show("You clicked the CheckBox control.");

break;

}

}

]]></mx:Script>

<mx:Button label="Click Me" id="button1"/>

<mx:CheckBox label="Select Me" id="cb1"/>

</mx:Application>