Created
March 4, 2015 07:32
-
-
Save theaspect/480f0566b9540d158d55 to your computer and use it in GitHub Desktop.
Nashorn two-way binding
This file contains hidden or 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
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import javax.script.ScriptException; | |
import java.lang.reflect.InvocationTargetException; | |
public class Script { | |
public static void main(String... args) throws ScriptException, IllegalAccessException, InvocationTargetException, InstantiationException { | |
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); | |
engine.eval("" + | |
"var Integration = Java.type('Script.Integration');\n" + | |
"var intObject = new Integration();\n" + | |
"print('SCRIPT Return from echo: ' + intObject.echo('Hello world'));\n" + | |
"intObject.info('someInfo');\n" + | |
"intObject.callback = function(name,info){print('SCRIPT callback{name:\"'+name+'\",info:\"'+info+'\"}')}\n" + | |
"intObject.info('someInfo');\n" | |
); | |
} | |
public static class Integration { | |
Callback callback; | |
String info; | |
public String echo(String out) { | |
System.out.println("JAVA echo"); | |
return out; | |
} | |
public void info(String info) { | |
System.out.println("JAVA setInfo"); | |
this.info = info; | |
if (callback != null) { | |
callback.onEvent("callback method", info); | |
} else { | |
System.out.println("JAVA No callback registered"); | |
} | |
} | |
public void setCallback(Callback callback) { | |
System.out.println("JAVA setCallback"); | |
this.callback = callback; | |
} | |
public Callback getCallback() { | |
System.out.println("JAVA getCallback"); | |
return callback; | |
} | |
} | |
@FunctionalInterface | |
public interface Callback { | |
public abstract void onEvent(String name, String param); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment