1

是否可以在 addEventListener 的末尾传递一个 var?

/// clickType declared elsewhere in code.
checkBoxFast.addEventListener(clickType, goFast("yes"));

function goFast(evt:Event=null,myVar:String)
{
trace(myVar);
}
4

4 回答 4

2

我想如果你想参数化你的事件处理我会建议将变量传递给事件。

- 创建自定义事件:

public class MyEvent extends Event {
    public var myVar:String;

    public function MyEventHistoryEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) {
        super(type, bubbles, cancelable);
    }
}

- 使用所需变量从事件分派器分派此事件:

var event:MyEvent = new MyEvent("eventType");
event.myVar = "yes";

dispatchEvent(event);

- 添加事件处理程序:

checkBoxFast.addEventListener("eventType", eventHandler);

protected function eventHandler(event:MyEvent):void {
trace(event.myVar);
}
于 2012-09-29T05:13:21.990 回答
1

另一种解决方案是使用匿名函数,如下所示:

checkBoxFast.addEventListener(clickType, function(e:Event):void{goFast("yes")});

function goFast(myVar:String)
{
    trace(myVar);
}
于 2012-09-29T10:09:53.967 回答
0

Creating custom event is best way I guess. But I was using sometimes different aproach. I dont know if it is good practice but it works in some cases.

public function test() {

        var myVar : String = "some value";
        addEventListener(MouseEvent.CLICK, onClick);


        function(e:Event){
            trace(myVar);
        }

    }
于 2012-09-29T10:00:59.857 回答
0

这是一个非常干净的方法:

checkBoxFast.addEventListener(clickType, goFast("yes"));

function goFast(myVar:String) {return function(e:Event) {
    trace(myVar);
}}

要注意匿名函数,它们不会让你在同一个地方结束监听器!如果你在你的应用程序中重复多次,它可能会变慢并冻结。

实际上,我真的建议您这样做:

var functionGoFast:Function = goFast("yes");
checkBoxFast.addEventListener(clickType, functionGoFast);

function goFast(myVar:String):Function {
  return function(evt:Event = null):void {
    trace(myVar);
  }
}

//checkBoxFast.removeEventListener(clickType, functionGoFast);

有关您的案例的更多示例和解释,请参阅此答案

于 2012-11-22T05:08:02.113 回答