我有以下javascript方法:
myFunc = function(callback) { callback.call(this, "hello", "world"); }
我正在传递一个实现'call'方法的java对象。在java调用方法中,我得到两个参数“hello”和“world”,但不是“this”(当然)。有没有办法从java访问'this'?
我将java与d3.js接口,d3以这种方式有很多回调,'this'是d3存储选择的地方。
谢谢
答案 0 :(得分:0)
我实际上并不是用Java编写的,而是JRuby。为了制作Java示例 我不得不简化下面的代码。也许这可以帮助一些人。如果不, 我会尝试做一个Java示例。
# Function f1 will call the callback methods cb1 and cb2 with 'this' variable
# This is just a notation for creating javascript function. It calls
# @browser.executeJavaScriptAndReturnValue(scrpt), whith the function
# body (everything between EOT) modified to make a valid javascript script.
# f1 is a function with 2 arguments cb1, and cb2 which should be the
# callback functions
f1 = B.function(<<-EOT)
(cb1, cb2) {
cb1.call(this, "banana", "milk");
cb2.call(this, "arroz", "feijao");
}
EOT
# Proc is a closure. It receives two arguments |food1, food2|. This will
# become a java object per JRuby´s magic
proc = Proc.new { |food1, food2| puts "I hate #{food1} and #{food2}" }
# now call method f1 passing proc as the first argument and the block as
# the second argument. So cb1 = proc and cb2 = <the block bellow>. Method
# 'send' grabs the given arguments, converts them to java objects and then
# calls jxBrowser 'invoke' method with the given arguments.
f1.send(proc) { |food1, food2| puts "eu gosto de #{food1} e #{food2}" }
执行此代码的结果是:
I hate banana and milk
eu gosto de arroz e feijao
可以看出,'this'变量刚刚消失......我希望能够 以某种方式捕获'this'变量,以便能够使用块中的上下文。我设法制定了一个允许捕获'this'变量的解决方法,但它需要将块包装在另一个javascript函数中。
这段代码的全部思想是允许JRuby开发人员编写Ruby代码并在jxBrowser中执行此代码,而无需使用任何javascript。下载mdarray-sol GEM或转到https://github.com/rbotafogo/mdarray-sol已经可以看到这方面的例子。在那里你可以看到使用JRuby使用d3.js的多个例子。
答案 1 :(得分:0)
请确保您按照https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript上的说明正确地使用call()
方法注入Java对象:
Java代码:
browser.addScriptContextListener(new ScriptContextAdapter() {
@Override
public void onScriptContextCreated(ScriptContextEvent event) {
Browser browser = event.getBrowser();
JSValue window = browser.executeJavaScriptAndReturnValue("window");
window.asObject().setProperty("java", new JavaObject());
}
});
...
public static class JavaObject {
public void call(JSValue window, String message) {
System.out.println(message);
}
}
JavaScript代码:
window.java.call(window, 'Hello Java!');