0

I am writing php framework that extracts Javascript blocks to merge, minify and execute them asynchronously.

So i like to delay Javascript code execution, to do that i wrap the javascript in

MyLib.then(function(){
//orignial code from the templates....
}

this works fine unless the wrapped code needs to create global variables (i am not the author of the wrapped code, so i do not want to fix that code) instead i like to run that code in a global execution context.

for example:

//excample code not within my controle  
var global="Hello World";

would become:

MyLib.then(function(){
   //excample code not within my controle  
   var global="Hello World";
}

the solution right now is to put the javascript into an string and then

MyLib.then(function(){
     $.globalEval("var global=\"Hello World\"";");
}

or with the globalEval call within my library

MyLib.then("var global=\"Hello World\"";")

but i would like to stick to the better readable version, which is also easier to debug for users of the framework.

MyLib.then(function(){
   var global="Hello World";
}

and change the execution context within my lib by using callback.call(window) or something like that, is that possible?

2 Answers2

0

Yea. You can add it to the window / document objects.

For example: window.var = "Hello"

When using the window object it can be accessed from anywhere. You could also create your own global object.

Manu Masson
  • 1,667
  • 3
  • 18
  • 37
  • 1
    @Keywan Ghadami What do you mean? – Manu Masson Oct 20 '15 at 10:54
  • the code var global="Hello World" stands as example for javascript that is written by other developers and should continue to run. Even if its wrapped within my code. I can not change that code, only the way how it's wrapped. – Keywan Ghadami Oct 20 '15 at 11:42
0

You can also declare your variable in global context and then initialize it in a scope:

var globalVariable;
MyLib.then(function(){
    globalVariable = "a value";
});

If your code already runs inside a scope you can go ahead with this:

(function(global){
    // my logic
    global.myVar = "a value";
})(this);
dude
  • 5,678
  • 11
  • 54
  • 81