Last active
August 13, 2016 09:30
-
-
Save jtulach/7102188 to your computer and use it in GitHub Desktop.
Counting button clicks in Java with low level JavaScript interaction
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 dew.demo.lowlevel; | |
import net.java.html.js.JavaScriptBody; | |
final class Java2JsAndBack implements Runnable { | |
private int cnt = 0; | |
@Override public void run() { | |
String msg = "I was pressed"; | |
if (++cnt > 1) { | |
msg += " " + cnt + " times"; | |
} | |
changeText("button", msg); | |
} | |
// | |
// Java/JS bridge utility methods. Visit | |
// http://bits.netbeans.org/html+java/1.3/net/java/html/js/package-summary.html | |
// to learn how to use the @JavaScriptBody annotation | |
// | |
@JavaScriptBody(args = { "id", "text" }, body = | |
"var e = window.document.getElementById(id);\n" + | |
"e.innerHTML = text;" | |
) | |
public static native void changeText(String id, String text); | |
@JavaScriptBody(args = { "id", "r" }, | |
javacall = true, body = | |
"var e = window.document.getElementById(id);\n" + | |
"e.onclick = function() {" + | |
" [email protected]::run()();" + | |
"};" | |
) | |
public static native void onclick(String id, Runnable r); | |
// | |
// initialization | |
// | |
static { | |
Java2JsAndBack handler = new Java2JsAndBack(); | |
onclick("button", handler); | |
} | |
} |
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
<button id="button">Press me!</button> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the live snippet by visiting its DEW at http://dew.apidesign.org/dew/#7102188