I have written a checkers game model which has a Board object that holds a bunch of Piece objects. The Piece objects have an event (pieceMoved) which they fire each time they are moved.
I am using EaselJS to render this game model in a canvas element.
The first thing I do is create an easeljs shape object to graphically represent each piece.
I wish to handle the pieceMoved event on the pieces' corresponding shape objects so that I can update the shapes location.
The code where I create the shapes and assign the event handlers looks something like this -
for (x=0;x<=(board_.getColCount()-1);x++) {
for (y=0;y<=(board_.getRowCount()-1);y++) {
var piece = board_.getPieceAt(x, y);
if (!piece) continue;
var circ = new Shape();
circ.eventHandler = function(pieceObj) {
this.x = pieceObj.x*squareSize;
this.y = pieceObj.y*squareSize;
}
piece.addEventHandler(circ.eventHandler);
....
The problem is that the 'this' keyword inside the event handler doesn't refer to the right thing. I also tried the following -
piece.addEventHandler(function(px) { return circ.eventHandler; });
But again, 'this' refers to the wrong object.
What is the proper way to do something like this?