0

I got this section of code I can't seem to make work. It seems to be a scoping issue I was wondering if you have any idea.

Here is the section of code I think is broken.

                click: function(layer) {
                    selectedR = r;
                    selectedC = c;
                    render();
                },

The problem is when I click on the image it executes the function, however the values for selectedR/selectedC are always getting set to 8,8 which implies it isn't grabbing the variable value from r,c until the function is actually clicked. Can you think of a way I can accomplish this? I basically want to know the r,c of the item I click on. I am using JQuery/JCanvas libraries if that helps. Below is the code in context.

var selectedR;
var selectedC;


function drawPieces(){
    for( var r = 0; r < 8; r++){
        for(var c = 0; c < 8; c++){
            var x = boardLeft + (c * tileWidth);
            var y = boardTop + (r * tileHeight);
            var piece = gameboard[r][c];

            if(piece.pieceCode == ChessPieceEnum.EMPTY){
                continue;
            }

            $("canvas").drawImage({
                layer: true,
                source: piece.pieceCode.normalImage,
                x: x, 
                y: y,
                cursor: "pointer",
                click: function(layer) {
                    selectedR = r;
                    selectedC = c;
                    render();
                },
                fromCenter: false
            });

            piece.x = x;
            piece.y = y;
        }
    }
}
EpicOfChaos
  • 822
  • 11
  • 23

1 Answers1

0

So it appears the layer object that is passed into the click functions is a reference to itself. So just add r/c to the layer object than you have access to it in the anonymous function.

function drawPieces(){
    for( var r = 0; r < 8; r++){
        for(var c = 0; c < 8; c++){
            var x = boardLeft + (c * tileWidth);
            var y = boardTop + (r * tileHeight);
            var piece = gameboard[r][c];

            if(piece.pieceCode == ChessPieceEnum.EMPTY){
                continue;
            }

            $("canvas").drawImage({
                layer: true,
                source: piece.pieceCode.normalImage,
                x: x, 
                y: y,
                r: r,
                c: c,
                cursor: "pointer",
                click: function(layer){
                    onPieceClick(layer.r, layer.c);
                },
                fromCenter: false
            });

            piece.x = x;
            piece.y = y;
        }
    }
}

function onPieceClick(r,c){
    selectedR = r;
    selectedC = c;
    render();
}
EpicOfChaos
  • 822
  • 11
  • 23