I have a 16x16 grid of buttons, and want to add an event listener to each of them so when clicked it will return its unique grid position number (anything between 0-255); What I have so far:
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);
}
}
}
}
Unfortunately every time the listener function is called by each button, it uses the last two values of i and j, which in this case return 255 for every button.
Any suggestions?