简体   繁体   English

Rhino,从多个javascript文件中添加代码

[英]Rhino, adding code from multiple javascript files

I am embedding some javascript in a Java application using Rhino. 我正在使用Rhino在Java应用程序中嵌入一些javascript。 I am following the example on the Rhino website, executing a script by calling the Context's evaluateString method and passing the actual script in as a String. 我正在关注Rhino网站上的示例,通过调用Context的evaluateString方法执行脚本并将实际脚本作为String传递。

I have a whole bunch of existing javascript code that I would like to make use of. 我有一大堆现有的javascript代码,我想利用它。 I don't want to concatenate it all into an enormous String and pass it in to evaluateString. 我不想将它全部连接成一个巨大的String并将其传递给evaluateString。 I would rather be able to load the code in so that I can call it from the code that I do pass into evaluateString (kind of like the AddCode method works in Microsoft's scripting control). 我宁愿能够加载代码,以便我可以从我传递给evaluateString的代码中调用它(有点像AddCode方法在Microsoft的脚本控制中工作)。 I would like to add code like I can currently add variables by using the ScriptableObject.putProperty method. 我想添加代码,就像我目前可以使用ScriptableObject.putProperty方法添加变量一样。

Is there a way to do this? 有没有办法做到这一点? Can someone provide a code snippet or a link to the documentation. 有人可以提供代码段或文档链接。 Thanks! 谢谢!

From the documentation and examples it looks like references to previously evaluated objects are controlled by scopes . 文档示例中可以看出,对先前评估的对象的引用由作用域控制。

Context context = Context.enter();
try {
  ScriptableObject scope = context.initStandardObjects();
  Object out = Context.javaToJS(System.out, scope);
  ScriptableObject.putProperty(scope, "out", out);
  context.evaluateString(scope,
      "function foo() { out.println('Hello, World!'); }", "<1>", 1, null);
  context
      .evaluateString(scope, "function bar() { foo(); }", "<2>", 1, null);
  context.evaluateString(scope, "bar();", "<3>", 1, null);
} finally {
  Context.exit();
}

(Rhino 1.7 release 2) (Rhino 1.7发布2)


I know some people use Rhino directly to get the latest version, but the Java 6 implementation can evaluate scripts like this: 我知道有些人直接使用Rhino来获取最新版本,但Java 6实现可以像这样评估脚本:

ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.eval("function foo() { println('Hello, World!'); }");
engine.eval("function bar() { foo(); }");
engine.eval("bar();");

In my code I had that need (utility scripts and such), and I just simply concatenated them together in a giant StringBuilder and evaled it (Java 6). 在我的代码中,我有这个需求(实用程序脚本等),我只是简单地将它们连接在一个巨大的StringBuilder中并对其进行了改进(Java 6)。 Its the only way since javascript can't do (without Java wrapper objects) otherJSScript.someUsefulFunction(). 它是自javascript无法做到的唯一方法(没有Java包装器对象)otherJSScript.someUsefulFunction()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM