javascripthtmlsyntaxhtml5-canvaseaseljs

Dynamic variable names with JavaScript and constructor: cloning an image with EaselJS dynamically to multiple canvases


I'm attempting to use dynamic variable names in JavaScript applied to a constructor. It's been much more difficult than expected. I've read about this issue in numerous forums and webpages but I can't find what I'm doing wrong.

I'm using a HTML5+JavaScript library called EaselJS but my problem it's not related to it but to JavaScript syntax! Here's my problem. I got this code:

stage1 = new Stage(document.getElementById("cnvs1"));
stage2 = new Stage(document.getElementById("cnvs2"));
stage3 = new Stage(document.getElementById("cnvs3"));

Here, the variables stage have assigned an Stage object which is initialized with canvas id cnvs This line (in the context of the rest of my code) works!

I'd like to simplify this to a single line with a for like this:

for(i = 0; i < 5; i++){
  //Of course this is wrong!
  stage[i] = new Stage(document.getElementById("cnvs[i]"));
}

This link here resumes how this can be done: With eval (a lot of people say it's not recommendable) and with window (recommended) Then if I do this (without the for to simplify even more):

var varname = "stage";
var i = 1;
window[varname + i] = new Stage(document.getElementById("cnvs_terminal1"));

The code still works. But I can't figure out how to accomplish a similar solution with the canvas id in quotes. These lines of code fail:

var i = 1;
var varname = "stage";
var varname2 = 'cnvs1';
var varname3 = "\"cnvs1\"";
var varname4 = "\"cnvs1" + i + "\"";

window[varname +i] = new Stage(document.getElementById(window[varname2]));
window[varname +i] = new Stage(document.getElementById(window[varname3]));
window[varname +i] = new Stage(document.getElementById(window[varname4]));

In these attempts even trying to pass the exact value I need (without the i) does not solve the problem. I'm backslashing quotes because I think they are necessary for the getElementbyId.

I'm certain there is a way to do this, maybe I don't know the syntax, maybe I don't know how to call variables with reference or by value properly, I don't know...

Edit

I am trying @cHao's suggestion, but I can't do that either! Keeping it simple, I set the for for i to be one only:

for (var i = 1; i <= 1; ++i) {
  //I use only one of the following lines at a time of course, but I'll write here my failing tries all together:
  stage[i] = new Stage(document.getElementById('cnvs'+i));
  stage[i-1] = new Stage(document.getElementById('cnvs'+i));

  //Hardcoding the first variable works!
  stage1 = new Stage(document.getElementById('cnvs'+i));
}

Half of the problem is solved, but what to do with the first variable?

Edit 2

More detail has been requested. Here's a copy/paste example. Just update the EaselJS and an image paths for this to work:

<!DOCTYPE HTML>
<html>
  <head>
    <script src="easeljs-0.4.0-26/lib/easel.js"></script>       
        
    <script type="text/javascript"> 
      function init() {
        //MY PROBLEM LIES HERE!!
        for (var i = 1; i <= 1; ++i) {
          //This code WORKS
          stage1 = new Stage(document.getElementById('cnvs'+i));
          //This code DOES NOT WORK
          //stage[i] = new Stage(document.getElementById('cnvs'+i));
          //stage[i-1] = new Stage(document.getElementById('cnvs'+i));
        }
        var images = "images/itzapic.jpg";
        bitmap = new Bitmap(images);
        stage1.addChild(bitmap);
        stage1.update();
        Ticker.addListener(window);
      }
            
      function tick() {
        stage1.update();
      }
    </script>        
  </head>
    
  <body onload="init()"> 
    <canvas id="cnvs1" width="140" height="82">
  </body>
</html>

Solution

  • Not sure i get the point of eval'ing or pre-figuring variable names and all that. Seems like you could just do like

    for (var i = 1; i <= 5; ++i) {
        stage[i] = new Stage(document.getElementById('cnvs' + i));
    }
    

    window["varname"] won't help unless varname is global, and...eh. You'll want to avoid globals if you can. Either way, you don't need to escape quotes -- you don't need quotes in the name itself at all unless your IDs have quotes in them (which, AFAIK is invalid anyway) or you're eval'ing (which is evil in itself).

    If you're looking to put the stages into an array (which seems like a better goal), you'll want your first stage to be stage[0]. In which case, set stage[i-1] instead of stage[i].

    And if you're trying to set stage1, stage2, etc...stop. Don't do that. You have a bunch of items, that you're treating alike...that's the kind of thing arrays were meant for. For one thing, notice how much easier it is to work with array elements than similarly-named variables? I wasn't even seeing the issue, because with arrays it's already a non-issue.

    As for your code...watch this.

    stage = [];
    
    function init() {
        for (var i = 1; i <= 1; ++i) {
            stage[i-1] = new Stage(document.getElementById('cnvs'+i));
        }
        var images = "images/itzapic.jpg";
        bitmap = new Bitmap(images);
        stage[0].addChild(bitmap);
        stage[0].update();
        Ticker.addListener(window);
    }
    
    function tick() {
        for (var i = 0; i < stage.length; ++i) {
            stage[i].update();
        }
    }
    

    Once we switch from the stage1 stage2 brokenness to using an array, now we can have as many stages as we want.