fro*_*ega 7 apache-flex flash events closures actionscript-3
此问题不仅与MouseEvent.CLICK事件类型有关,而与AS3中已存在的所有事件类型有关.我读了很多关于自定义事件的内容,但直到现在我还无法弄清楚如何做我想做的事情.我打算解释一下,希望你理解:
以下是我的情况说明:
for(var i:Number; i < 10; i++){
var someVar = i;
myClips[i].addEventListener(MouseEvent.CLICK, doSomething);
}
function doSomething(e:MouseEvent){ /* */ }
Run Code Online (Sandbox Code Playgroud)
但我希望能够将someVar作为参数传递给doSomething.所以我尝试了这个:
for(var i:Number; i < 10; i++){
var someVar = i;
myClips[i].addEventListener(MouseEvent.CLICK, function(){
doSomething(someVar);
});
}
function doSomething(index){ trace(index); }
Run Code Online (Sandbox Code Playgroud)
这种作品但不像我期望的那样.由于函数闭包,当实际触发MouseEvent.CLICK事件时,for循环已经结束并且someVar保持最后一个值,例子中的数字9.因此,每个影片剪辑中的每次点击都会调用doSomething传递9作为参数.这不是我想要的.
我认为创建自定义事件应该可以工作,但是当我触发MouseEvent.CLICK事件并将参数传递给它时,我找不到触发自定义事件的方法.现在我不知道这是不是正确的答案.
我该怎么做以及如何做?
您确实需要扩展事件类以使用额外参数创建自己的事件.将函数放在addEventListener(匿名函数)中是一个内存泄漏的方法,这是不好的.看一下以下内容.
import flash.events.Event;
//custom event class to enable the passing of strings along with the actual event
public class TestEvent extends Event
{
public static const TYPE1 :String = "type1";
public static const TYPE2 :String = "type2";
public static const TYPE3 :String = "type3";
public var parameterText:String;
public function TestEvent (type:String, searchText:String)
{
this.parameterText = searchText;
super(type);
}
}
Run Code Online (Sandbox Code Playgroud)
当你创建一个新的事件,如
dispatchEvent(new TestEvent(TestEvent.TYPE1, 'thisIsTheParameterText'))" ;
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样听这个事件
someComponent.addEventListener(TestEvent.TYPE1, listenerFunction, true , 0, true);
Run Code Online (Sandbox Code Playgroud)
在函数'listenerFunction'中,event.parameterText将包含您的参数.
因此,在myClips组件中,您将触发自定义事件并侦听该事件,而不是Click事件.
在不了解您的应用程序的情况下,您似乎更应该使用目标来传递参数,或者扩展MouseEvent.不过,前者更符合惯例.例如,如果您在"剪辑"对象上暴露了整数公共属性(无论它是什么):
public class MyClip
{
public var myPublicProperty:int;
public function MyClip() { //... }
}
for (var i:int = 0; i < 10; i++)
{
myClips[i].myPublicProperty = i;
myClips[i].addEventListener(MouseEvent.CLICK, doSomething);
}
Run Code Online (Sandbox Code Playgroud)
...然后,在事件监听器中,您可以使用事件的target或currentTarget属性检索该属性(在您的情况下可能是currentTarget):
function doSomething(event:MouseEvent):void
{
trace(event.currentTarget.myPublicProperty.toString());
}
Run Code Online (Sandbox Code Playgroud)
应该这样做!祝好运.
| 归档时间: |
|
| 查看次数: |
48035 次 |
| 最近记录: |