我有一个16x16的按钮网格,并且希望为每个按钮添加一个事件监听器,因此单击它时将返回其唯一的网格位置编号(0到255之间的任何值); 我有什么至今:动态地将参数传递给事件监听器AS3
public static const GRID_SIZE:Number = 16;
private var i:int;
private var j:int;
// Constructor
public function Grid()
{
for (i = 0; i < GRID_SIZE; i++)
{
for (j = 0; j < GRID_SIZE; j++)
{
// Creates new instance of GridButton, a custom class that extends SimpleButton
var button:GridButton = new GridButton();
// Arranges buttons into a grid
button.x = (i + 1) * button.width;
button.y = (j + 1) * button.height;
// Create unique value for grid position
var position:Number = i * GRID_SIZE + j;
// Add listener to button, with position as extra param
button.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) : void { buttonClick(e, position) });
// Adds button to Sprite
addChild(button);
}
}
}
}
不幸的是每一个听者的功能是由每个按钮调用的时候,它使用i和j的最后两个值,它在每一个按钮这种情况下返回255。
有什么建议吗?
您也可以使用闭包。检查我的答案以下问题:http://stackoverflow.com/questions/7396845/how-to-use-a-method-of-a-class-inside-a-callback-function-in-actionscript/7412402# 7412402 –
除非您完全理解使用闭包的后果,否则不应使用它们。 –