Module System Implementation

Sep 25, 2011 at 4:35 PM

 

Is ther a way to do something like this ?

 

string script1 = "requires ("module.js");   function foo () { return bar (); } ";

string script2 = "function bar () { return "test bar string"; } ";

var engine = new Jurassic.ScriptEngine();

 engine.OnRequire = (Func<string>)(x => x == "module.js" ? script2 : null);

 engine.Evaluate(script1);

 Console.WriteLine(engine.CallGlobalFunction <string>("foo"));

 

 

Sep 25, 2011 at 7:46 PM

Sure you can, but you can't write it like that. What you can do is this:

var script = "require('module.js'); function foo() { return bar(); };";
var dict = new Dictionary<string, string>
{
    {"module.js", "function bar() { return 'test bar string'; };" }
};
var engine = new Jurassic.ScriptEngine();
engine.SetGlobalFunction(new Action<String>(name =>
{
    if(dict.ContainsKey(name))
        engine.Execute(dict[name]);
});
engine.Execute(script);
Console.WriteLine(engine.CallGlobalFunction<string>("foo"));