栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用require.js和Java / Rhino解析模块

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用require.js和Java / Rhino解析模块

require.js在rhino上运行良好。最近,我在一个项目中使用了它。

  1. 您必须确保使用r.js(不是require.js),犀牛的require.js的修改版本。
  2. 您必须扩展
    ScritableObject
    类才能实现
    load
    print
    运行。调用时
    require(["a"])
    ,将调用此类中的load函数,您可以调整此函数以从任何位置加载js文件。在以下示例中,我从加载
    classpath
  3. 您必须
    arguments
    在sharedscope中定义属性,如下面的示例代码所示
  4. (可选)您可以使用配置子路径
    require.config
    ,以指定classpath内js文件所在的子目录。

JsRuntime支持

public class JsRuntimeSupport extends scriptableObject {    private static final long serialVersionUID = 1L;    private static Logger logger = Logger.getLogger(JsRuntimeSupport.class);    private static final boolean silent = false;    @Override    public String getClassName() {        return "test";    }    public static void print(Context cx, scriptable thisObj, Object[] args, Function funObj) {      if (silent)        return;        for (int i = 0; i < args.length; i++)          logger.info(Context.toString(args[i]));    }    public static void load(Context cx, scriptable thisObj, Object[] args, Function funObj) throws FileNotFoundException, IOException {        JsRuntimeSupport shell = (JsRuntimeSupport) getTopLevelScope(thisObj);        for (int i = 0; i < args.length; i++) { logger.info("Loading file " + Context.toString(args[i])); shell.processSource(cx, Context.toString(args[i]));        }    }    private void processSource(Context cx, String filename) throws FileNotFoundException, IOException {        cx.evaluateReader(this, new InputStreamReader(getInputStream(filename)), filename, 1, null);    }    private InputStream getInputStream(String file) throws IOException {        return new ClassPathResource(file).getInputStream();    }}

样例代码

public class RJsDemo {    @Test    public void simpleRhinoTest() throws FileNotFoundException, IOException {    Context cx = Context.enter();    final JsRuntimeSupport browserSupport = new JsRuntimeSupport();    final scriptableObject sharedScope = cx.initStandardObjects(browserSupport, true);    String[] names = { "print", "load" };    sharedScope.defineFunctionProperties(names, sharedScope.getClass(), scriptableObject.DONTENUM);    scriptable argsObj = cx.newArray(sharedScope, new Object[] {});    sharedScope.defineProperty("arguments", argsObj, scriptableObject.DONTENUM);    cx.evaluateReader(sharedScope, new FileReader("./r.js"), "require", 1, null);    cx.evaluateReader(sharedScope, new FileReader("./loader.js"), "loader", 1, null);    Context.exit();  }}

loader.js

require.config({    baseUrl: "js/app"});require (["a", "b"], function(a,  b) {    print('modules loaded');});

js/app
目录应该在您的类路径中。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号