tags:

views:

272

answers:

2

I have an interesting problem that I'm unsure how best to solve.

I have JS scripts which contain the following:

   var obj = new namespace.MyObjectName("key", [12, 11, 22, 33, 454, 552, 222], [33, 22, 33, 11, 22, 222, 111]);

   namespace.MyObjectName = function(keyName, data1, data2) {
 this.myData1 = data1;
 this.myData2 = data2;

 this.holder = [
        [keyName, [myData1, myData2]]
 ];
   };

   namespace.MyObjectName.prototype.DoSomething = function(arg1, argArray) {
 this.globalVar = [
      "Display " + arg1 + " into string using " + argArray[0] + "<br> for visual purposes",

      "Display " + arg1 + " into string using " + argArray[2] + "<br> for visual purposes"
    ];
   };

Automation is creating copies of these JS files, each containing the same declaration of the object as per above, with filenames along the lines of:

  • file1.js
  • file2.js

The per file difference is that the DoSomething method name contents are always different/generated, as are the array values passed to the constructor.

All of the above was just fine during the life of that JS being used standalone.


What I want to do now is have an HTML page load 1 or more of these files dynamically (for later comparison by code to be written), for which I'll probably go with this answer, however since each script declares the object the same way, I am faced with figuring out how to stop them trampling over one another when I load multiple copies.

Here are some options I am considering:

  1. Write the JS in such a way that each script file object is uniquely namespaced, but when loaded registers itself somehow with a master piece of JS code in the HTML which holds onto all the object references
  2. Write the HTML in such a way that each script is loaded in a fenced-off way (insofar as i know, there isn't a way to do this in JS, but I could be wrong)
  3. Some other method(s) unknown that people might have ideas on

My current bias is towards (1) but I'm putting the whole thing out for discussion since that approach might have inherent problems or others may be clearly demonstrated as superior.

+1  A: 

Regarding (2), it's possible to run javascript in a sandbox by using an iframe, check out for instance Dean Edwards' Sandbox.eval() or the Slickspeed Selectors Test.

Kristian J.
A: 

I dont really understand the problem, but to avoid the trampling of the namespace you could do:

var namespace = namespace || function() {}
Luca Matteis
I'm not quite sure what that does? .. assigning the existing var namespace to itself, else empty object?
j pimmel
The empty object is just an example, you can replace that with your own object.
Luca Matteis