I'm having a problem where I create a two-dimensional array (called "grid") that contains an object (the "square"). In this simplified example the object just keeps track of how many times the square has been selected (clicked).
My initial grid data looks like this after it's created...
this.grid = [
[{"selected":0},{"selected":0},{"selected":0}]
,[{"selected":0},{"selected":0},{"selected":0}]
,[{"selected":0},{"selected":0},{"selected":0}]
];
Currently when a square is clicked and I try to increment the selected value in only one object, using something as simple as this.grid[x][y].selected += 1;
. Instead all values in the row are incremented and I end up with...
[ [{"selected":0},{"selected":1},{"selected":0}]
,[{"selected":0},{"selected":1},{"selected":0}]
,[{"selected":0},{"selected":1},{"selected":0}] ]
An entire row had selected incremented, not just one object. Not what I want. :(
I believe the problem is with the grid's array creation, because it works if I hard-code the grid's value. What might be causing the problem and what is the solution?
Here's the JavaScript code...
function GridClass () {
this.$grid = $('.grid');
this.grid = [[]];
this.createGrid = function () { // I think this is where the problem lies
var baseSize = 3;
this.grid = [];
var blankYArray = [];
for (var y = 0; y < baseSize; y++) {
blankYArray.push({
"selected" : 0
});
}
for (var x = 0; x < baseSize; x++) {
this.grid.push(blankYArray);
}
}
this.selectSquare = function (x, y) {
this.grid[x][y].selected += 1;
this.drawGrid();
}
this.drawGrid = function () {
var h = "", rowClass = "";
var xLen = this.grid.length;
var yLen = this.grid[0].length;
for (var y = 0; y < yLen; y++) {
for (var x = 0; x < xLen; x++) {
var g = this.grid[x][y];
h += '<div class="' + rowClass
+ ' alt' + g.selected + '"'
+ ' data-x="' + x + '"'
+ ' data-y="' + y + '">'
+ x + "," + y + '</div>';
}
h += '<br />';
}
this.$grid.html(h);
}
this.createGrid();
this.drawGrid();
}
grid = new GridClass();
grid.$grid.on("click", "div", function(e){ // Click event for each square
var $thisSquare = $(this);
var x = $thisSquare.data("x");
var y = $thisSquare.data("y");
grid.selectSquare(x, y);
});
And the HTML is just: <div id="gridFrame"><div class="grid"></div></div>
The whole thing (including the CSS) is on jsfiddle here: http://jsfiddle.net/luken/fu4yW/