Dynamic Stage name in EaselJS

只愿长相守 提交于 2019-12-24 01:26:17

问题


I'm currently working on a site designed to display multiple canvases at the same time, without knowing which canvases it's going to display in advance (a PHP script creates the list).

The idea is to have multiple script files (one per canvas) be read by (typically) a single handler which will populate the individual stages.

stage = new createjs.Stage(context);

I'm stuck here. At the time I create a given stage, I know the name of the canvas I want to attach it to (for instance, stageA) and it's available in JavaScript in the variable named context. In this situation, I need to create an easeljs stage named stageA; the problem is I can't know in advance I won't need stageB instead of stageA so the created stage's name needs to be dynamic (equal to context). I tried something along the lines of

eval(context) = new createjs.Stage(context);

but it's not working as is.

(I also need to be able to operate on this dynamically named stage, ie be able to do

stageA.update();

for instance, without knowing stageA is called stageA but just based on context.)

Any suggestion?


回答1:


You can use bracket notation for global variables with either windows["stageA"] or if you know you are in global scope this["stageA"]

So if you have a context in global scope and you have a string with its variable name then you can access it via bracket notation like so

var stageA = // context of canvas
var stageName = "stageA"
var theStage = window[stageName];

Now theStage references stageA.

theStage.clearRect(0,0,100,100); 
// same as
stageA.clearRect(0,0,100,100);

All object attributes can be accessed via either dot notation ie window.alert or braket notation ie window["alert"]. As braket notation takes a string you can use a variable in its place.

Another example

   var myObj = {
       attributeA : 10,
   }
   console.log(myObj.attributeA); // output 10;
   console.log(myObj["attributeA"]); // output 10;
   var attributeName  = "attributeA";
   console.log(myObj[attributeName]); // output 10;

The global scope is called window but most people drop the window and directly reference the global scope. EG window.alert is the same as alert or window.requestAnimationFrame is the same as requestAnimationFrame

The global scope is also called this but you will need to know you are in global scope. If you are confident then this["alert"] or window["alert"] or alert or window.alert or this.alert are all the same reference if you are in global scope.



来源:https://stackoverflow.com/questions/34966537/dynamic-stage-name-in-easeljs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!