我有一個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 –
除非您完全理解使用閉包的後果,否則不應使用它們。 –