使用嵌套的函数作为事件监听器<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

         除了将事件监听器函数的名字传递给addEventListener()方法,你还可以定义一个内部函数(也可以理解为闭包)

 

         在下面的例子中,当按钮被点击,嵌套的函数就被调用:

 

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

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

<mx:Script><![CDATA[

import mx.controls.Alert;

private function initApp():void {

b1.addEventListener("click",

function(e:Event):void {

Alert.show("The button was clicked.");

}

);

}

]]></mx:Script>

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

</mx:Application>

 

         闭包函数除了可以在对象或类中创建,还可以在一个方法被调用时创建。闭包函数将保持它被定义时的范围。当它作为一个参数或一个返回值被传递到不同的范围时,将产生有趣的结果。

 

         例如,下面的代码创建了两个函数。叫做foo()的函数返回一个叫做retArea()的用来计算矩形面积的嵌套函数,叫做bar()的函数调用foo()并且将它返回的闭包函数保存在一个叫做myProduce的变量中,bar()还定义了叫做x的本地变量,并赋值2。当闭包函数myProduct()被调用时,它继续持有在foo()中定义的变量xbar()函数将返回的数值显示在TextInput控件中,但不是8

 

<?xml version="1.0"?>

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

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

<mx:Script><![CDATA[

[Bindable]

private var answer:String;

private function foo():Function {

var x:int = int(ti1.text);

function rectArea(y:int):int { // function closure defined

return x * y;

}

return rectArea;

}

private function bar():void {

var x:int = 2; // ignored

var y:int = 4; // ignored

var myProduct:Function = foo();

answer = myProduct(int(ti2.text)); // function closure called

}

]]></mx:Script>

<mx:Form width="107">

<mx:FormItem label="X">

<mx:TextInput id="ti1" text="10" width="37" textAlign="right"/>

</mx:FormItem>

<mx:FormItem label="Y" width="71">

<mx:TextInput id="ti2" text="20" width="38" textAlign="right"/>

</mx:FormItem>

<mx:Label id="label1" text="{answer}" width="71" textAlign="right"/>

</mx:Form>

<mx:Button id='b1' label="Compute Product" click="bar()"/>

</mx:Application>

        

         如果你传递给addEventListener()方法的监听器是一个嵌套的内部函数,那就不要将useWeakReference参数的值设定为true。例如:

 

addEventListener("anyEvent",

function(e:Event) { /* My listener function. */ },

false, 0, true)

 

         在这个例子中,如果将ture作为最后一个参数的值将导致意料之外的结果。对于Flex,内部函数其实就是一个对象,并且可以被垃圾回收释放。如果你将useWeakReference参数设定为true,就像上面例子里展示的那样,那么将不会有内部函数的长久的引用,在下一次回收时,可能会释放这个函数,并且当事件再次被触发时,函数将无法被调用。

 

         如果还有内部函数的其他引用,那么垃圾回收就不会释放它。

 

       类级的成员函数将不会被垃圾回收,这样你就可以将useWeakReference参数设定为true