Hi,
I've just started exploring Rhino and one of the first things I'd like
to do is add a global "println" function that my JS scripts can use, and
then add more functions. The idea is that the added function must be
able to access internal state so my first attempt was to create a
ScriptableObject-based class with a method called "println" and use it
as a starting scope as in:
stdlib = new MyStdLib();
cx.initStandardObjects(stdlib)
Script s = ...
s.exec(cx, stdlib);
...
This didn't work, and after a lot of trial and error I got to a point
where the following works:
MyStdLib stdlib = new MyStdLib(zr);
Context cx = jscf.enterContext();
Scriptable scope = cx.initStandardObjects(stdlib);
Script s = ...
s.exec(cx, scope);
and the MyStdLib class looks like:
class MyStdLib extends ScriptableObject
{
private InternalData zr;
protected MyStdLib(InternalData zr)
{
this.zr = zr;
try {
/* This is the important bit */
FunctionObject println = new FunctionObject("println",
MyStdLib.class.getDeclaredMethod("js_println", Context.class,
Scriptable.class, Object[].class, Function.class), this);
this.put("println", this, println);
} catch (Exception ex) {
Logger.getLogger(MyStdLib.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String getClassName() {
return "MyStdLib";
}
protected static Object js_println(Context cx, Scriptable thisObj,
Object[] args, Function func)
{
if (!(thisObj instanceof MyStdLib)) {
Context.reportError("Not based in MyStdLib");
return null;
}
MyStdLib stdlib = (MyStdLib) thisObj;
for (int i = 0; i < args.length; i++) {
stdlib.zr.out.print(args[i]);
if (i != args.length-1)
stdlib.zr.out.print(" ");
}
stdlib.zr.out.println();
return null;
}
}
The question is: this looks somewhat "dirty" - isn't there a way I can
simply declare functions and they get automagically exported to the JS
scope? I tried creating jsFunction_println in MyStdLib but it isn't
picked up.
_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino