如何向事件监听器传送额外的参数

如何向事件监听器传送额外的参数


问题摘要

在FLEX文档中所述的是,如果你要向监听器传送参数,那么你最好使用MXML标签,但是在这里要展示给你的是如何使用AS脚本完成。

解决摘要

使用内联函数

解释

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);
});



myPrivateSpecialObject = {name:"Special Ingredients for Apple"};

OtherButtonButton.addEventListener(MouseEvent.CLICK,function (e:MouseEvent) : void {
ABCButtonListener(e,myPrivateSpecialObject);
});

}


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.


Related files for download


bin-release1.zip

main.swf

你可能感兴趣的:(apple,脚本,Flex)