On Mon, Nov 22, 2010 at 5:20 PM, Ian Stevens <[email protected]> wrote:

> On 2010-11-22, at 4:00 PM, Daryl Stultz wrote:
>
> So you can continue what you're doing (ie., init your Scriptable with
> functions to be accessed globally) but create scopes off your top-level
> scope (this) using Context.newObject().
>
> I tried this approach out and it does solve my problem. I wasn't familiar
with newObject() as I wasn't intentionally trying to create a shared scope.
I opted for a simpler approach which makes my code a little more clear.

Thanks for your help.

For the benefit of anyone discovering the thread, my class no longer extends
ScriptableObject and my call to run the JavaScript looks more or less like
this:

Object result = null;
// Associate a new Context with this thread (or get existing)
Context context = ContextFactory.getGlobal().enterContext();
try {
executionCount++;
if (executionCount == 1) {
// provide acccess to "environment" to js api objects
context.putThreadLocal(THREAD_LOCAL_KEY_JS_EVALUATOR, this);

// security - filter classes available to JavaScript
context.setClassShutter(getClassShutter());
 // wrap factory (currently to get primitives as-is)
WrapFactory wrapFactory = new WrapFactory();
wrapFactory.setJavaPrimitiveWrap(false);
context.setWrapFactory(wrapFactory);
}
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed.
*ScriptableObject scope = context.initStandardObjects();*
// standard imports / aliases
ScriptableObject.putProperty(*scope*, "Blah", new NativeJavaClass(scope,
blah.Blah.class));
// Define global functions
String[] names = { "logInfo", "logWarning", "logError" };
*scope*.defineFunctionProperties(names, this.getClass(),
ScriptableObject.DONTENUM);

// Run the script
context.evaluateString(*scope*, javaScript, "<" + scriptedEntityId + ">", 1,
null);
Object fObj = scope.get(functionName, scope);
if (fObj instanceof Function) {
Function function = (Function) fObj;
result = function.call(context, scope, scope, functionArgs);
} // no such function found, so don't do anything
} catch (RhinoException exc) {
throw exc;
} finally {
executionCount--;
if (executionCount == 0) {
context.removeThreadLocal(THREAD_LOCAL_KEY_JS_EVALUATOR);
}
Context.exit();
}
if (result instanceof org.mozilla.javascript.NativeJavaObject) {
result = ((org.mozilla.javascript.NativeJavaObject) result).unwrap();
}
return result;

-- 
Daryl Stultz
_____________________________________
6 Degrees Software and Consulting, Inc.
http://www.6degrees.com
http://www.opentempo.com
mailto:[email protected]
_______________________________________________
dev-tech-js-engine-rhino mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-tech-js-engine-rhino

Reply via email to