Search code examples
javascripthtml5-canvaskineticjs

KineticJS Adding Events to Objects held in an Array


for (var x = 0; x < 10; x++) {
            //var xx = x;
            for (var y = 0; y < 10; y++) {
                //var yy = y;
                displayboxs[x][y][1].on('click', function() {
                    displayboxs[x][y][0] = 'P';
                });
            }
        }

so this is the code i want to run however the displaboxs[x][y][0] = 'P'; part gives an error. I found that trying to change any array the way I am trying to doesn't work, unfortunately however this is the only way I can do it unless I add each event manually (i'd rather not). I also found that by storing the x and y variables in another i can prevent the error (the portions of the code that are commented out shows this) however i get strange results. For example if I print the area of the array that was changed RIGHT after it was changed it will be 'P' however after i have changed many locations on the array to 'P' and print the whole array all the elements will still be set to default exept the last spot in the array which will be 'P'. Weird right? All suggestions are appreciated!!! Thanks for reading guys.


Solution

  • One problem is that x,y are long out-of-scope when any click is fired.

    Refactor by giving each displayboxs[x][y][1] a reference to the displayboxs[x][y][0] that it should alter when clicked.

    Something like this (warning...untested code!):

    for (var x = 0; x < 10; x++) {
        for (var y = 0; y < 10; y++) {
            displayboxs[x][y][1].on('click', function() {
                this.myZero = 'P';
            });
            (displayboxs[x][y][1]).myZero=displayboxs[x][y][0];
        }
    }