Problem
as Flex documentation states, the way to pass additional parameters to event listener is to use MXML tag., here is how to archive that using ActionScript.
Solution
Using Inline Function
Detailed explanation
solution is very simple, basically for following scenario :
arbitrary button called ABCButton,function ABCButtonListener needs to listen to click event and also receive extra parameter
引用
"myPrivateSpecialObject"
object.
you do following :
private function ABCButtonListener(e:MouseEvent,specialObj:Object):void
{
Alert.show(specialObj.name);
}
private function methodWhereyouDostuffAndRegisterListener(): void
{
var myPrivateSpecialObject:Object = {name:"Special String Ingredients for Orange"};
ABCButton.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent) :void
{
ABCButtonListener(e,myPrivateSpecialObject);
});
}
P.S -----------------
you can use same structure to register listener for more than one button,for example :
private function methodWhereyouDostuffAndRegisterListener(): void {
var myPrivateSpecialObject:Object = {name:"Special String
Ingredients for Orange"};
ABCButton.addEventListener(MouseEvent.CLICK,function
(e:MouseEvent) : void {
ABCButtonListener(e,myPrivateSpecialObject);
// if removing event listener is desired uncomment below:
//IEventDispatcher(e.currentTarget).removeEventListener(e.type,arguments.callee);
});
myPrivateSpecialObject = {name:"Special Ingredients for
Apple"};
OtherButtonButton.addEventListener(MouseEvent.CLICK,function
(e:MouseEvent) : void {
OtherButtonButtonListener(e,myPrivateSpecialObject);
// if removing event listener is desired uncomment below:
//IEventDispatcher(e.currentTarget).removeEventListener(e.type,arguments.callee);
});
}
above code registers same listener for two buttons but before registering second listener , we try to modify
引用
myPrivateSpecialObject
. so, reference is changed to have different value, but if you assume now each listener received different value , its not correct, they will both received latest assigned value . overall inline function is good technique to pass any number of parameters to a listener as long as listener is ready for those parameters.
UPDATE: way to remove linine functions from event listeners afterwards.
basically, if you want to remove inline function as listener from DIspatcher, there is two ways,
one is to add it as weakRefference, but second is even better:
just add this inside the Listener Function:
IEventDispatcher(e.currentTarget).removeEventListener(e.type,arguments.callee);