Is it possible to pass a var at the end of an addEventListener?
/// clickType declared elsewhere in code.
checkBoxFast.addEventListener(clickType, goFast("yes"));
function goFast(evt:Event=null,myVar:String)
{
trace(myVar);
}
Is it possible to pass a var at the end of an addEventListener?
/// clickType declared elsewhere in code.
checkBoxFast.addEventListener(clickType, goFast("yes"));
function goFast(evt:Event=null,myVar:String)
{
trace(myVar);
}
I guess if you want to parametrize your event handing I would suggest passing variables to the Event.
-Create a custom event:
public class MyEvent extends Event {
public var myVar:String;
public function MyEventHistoryEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) {
super(type, bubbles, cancelable);
}
}
-Dispatch this event from the event dispatcher with the required variable:
var event:MyEvent = new MyEvent("eventType");
event.myVar = "yes";
dispatchEvent(event);
-Add an event handler:
checkBoxFast.addEventListener("eventType", eventHandler);
protected function eventHandler(event:MyEvent):void {
trace(event.myVar);
}
Another solution would be to use an anonymous function like so:
checkBoxFast.addEventListener(clickType, function(e:Event):void{goFast("yes")});
function goFast(myVar:String)
{
trace(myVar);
}
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);
}
}
Here's a pretty clean way:
checkBoxFast.addEventListener(clickType, goFast("yes"));
function goFast(myVar:String) {return function(e:Event) {
trace(myVar);
}}
BUT beware anonymous functions, they won't let you end the listener in the same place it was made! If you keep repeating it like that many times in your application, it may get slow and freeze.
Actually, I really recommend you to do it like this:
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);
See this answer for more examples and explanations on your case.