Question

I have an array full of code that needs to be executed. It's part of a project using kinetic.js for HTML5 canvas.

I run a for loop to go through this array and use eval() to execute the code from the array. The array is called tiles and one part may look like this:

context.fillStyle="rgb(255,255,255)";
context.beginPath();
context.moveTo(256,197);
context.lineTo(177,241);
context.bezierCurveTo(172,237,167,232,162,228);
context.fill();

Now I have my for loop combined with the normal kinetic code to go through the array, execute the code and create shapes on my canvas. For example:

var layer = new Kinetic.Layer();
for (var i=0 ;i<5; i++) {
  var tile = new Kinetic.Shape({
    sceneFunc: function(context){ eval(tiles[i]); }
  });
  layer.add(tile);
}
stage.add(layer);

But this only adds one of the array items!! What the hell is going on? This is super confusing because if I write out the for loop, it works. Like this:

var tile = new Kinetic.Shape({
  sceneFunc: function(context){ eval(tiles[0]); }
});
layer.add(tile);

var tile = new Kinetic.Shape({
  sceneFunc: function(context){ eval(tiles[1]); }
});
layer.add(tile);

var tile = new Kinetic.Shape({
  sceneFunc: function(context){ eval(tiles[2]); }
});
layer.add(tile);

etc...
Was it helpful?

Solution

Closure:

var layer = new Kinetic.Layer();
for (var i=0 ;i<5; i++) {
  (function(num) {
     var tile = new Kinetic.Shape({
       sceneFunc: function(context){ eval(tiles[num]); }
     });
     layer.add(tile);
  }(i));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top