开箱即用:只需2 行额外的优雅代码即可解决这个古老的难题。
stage.addEventListener(MouseEvent.CLICK, onClick(true, 123, 4.56, "string"));
function onClick(b:Boolean, i:int, n:Number, s:String):Function {
return function(e:MouseEvent):void {
trace("Received " + b + ", " + i + ", " + n + " and " + s + ".");
};
}
但最重要的是,稍后您很可能需要删除侦听器以释放资源,因此+1 行将其存储在变量中:
var functionOnClick:Function = onClick(true, 123, 4.56, "string");
stage.addEventListener(MouseEvent.CLICK, functionOnClick);
function onClick(b:Boolean, i:int, n:Number, s:String):Function {
return function(e:MouseEvent):void {
trace("Received " + b + ", " + i + ", " + n + " and " + s + ".");
};
}
您将能够正常删除它:
trace("Before: " + stage.hasEventListener(MouseEvent.CLICK));
stage.removeEventListener(MouseEvent.CLICK, functionOnClick);
trace("After: " + stage.hasEventListener(MouseEvent.CLICK));
这是一个更详细的动态示例来证明其用途:
function onClick(s:String):Function {
return function(e:MouseEvent):void {
trace("The square " + s + " at x = " + e.currentTarget.x + "px was clicked");
};
}
var myFunctions:Array = new Array();
for (var i:int = 0; i < 10; i++) {
myFunctions.push(onClick("#" + (i+1)));
}
for (i = 0; i < myFunctions.length; i++) {
var square:Sprite = new Sprite();
square.name = "sqr" + i;
square.addChild(new Bitmap(new BitmapData(20, 20, false, 0)));
square.x = 5 + 25 * i;
square.addEventListener(MouseEvent.CLICK, myFunctions[i]);
stage.addChild(square);
}
没有通过动态对象的属性,没有自定义类,没有松散的功能,没有范围重叠。正是逻辑所期望的:您只是将参数传递给它。
要正确删除每个侦听器,您可以稍后这样做:
for (i = 0; i < myFunctions.length; i++) {
square = stage.getChildByName("sqr" + i) as Sprite;
trace("Before (#" + (i+1) + "): " + square.hasEventListener(MouseEvent.CLICK));
square.removeEventListener(MouseEvent.CLICK, myFunctions[i]);
trace("After (#" + (i+1) + "): " + square.hasEventListener(MouseEvent.CLICK));
stage.removeChild(square);
}
恕我直言,这是最简单但最可靠的方法。