Created
December 10, 2013 19:45
-
-
Save purplefox/7896892 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.vertx.java.platform.impl; | |
import javax.script.*; | |
import jdk.nashorn.api.scripting.ScriptUtils; | |
public class HandlerScopeTest { | |
public static void main(String[] args) { | |
new HandlerScopeTest().run(); | |
} | |
private String script1 = | |
"var myobj = { \n" + | |
" setCallback: function(cbk) { \n" + | |
" _javaobject.setCallback(cbk) \n" + | |
" } \n" + | |
"} \n" + | |
"// Try setting cbk - this works fine \n" + | |
"myobj.setCallback(function() { \n" + | |
"}); \n" + | |
"_javaobject.setObject(myobj);"; | |
// But setting callback from different scope fails! | |
private String script2 = | |
"myobj.setCallback(function() { \n" + | |
"}); \n"; | |
private void run() { | |
try { | |
ScriptEngineManager factory = new ScriptEngineManager(); | |
ScriptEngine engine = factory.getEngineByName("nashorn"); | |
// Run script1 in it's own scope | |
ScriptContext ctx = new SimpleScriptContext(); | |
Bindings bindings = engine.createBindings(); | |
bindings.put("_javaobject", this); | |
ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE); | |
engine.eval(script1, ctx); | |
// And this one in another scope | |
ctx = new SimpleScriptContext(); | |
bindings = engine.createBindings(); | |
bindings.put("myobj", myobj); | |
ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE); | |
engine.eval(script2, ctx); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
private Object myobj; | |
public void setObject(Object obj) { | |
myobj = ScriptUtils.wrap(obj); | |
} | |
public void setCallback(Runnable cbk) { | |
System.out.println("Setting callback on Java object: " + cbk); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment