我可不是真正的编码在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'变量,但它需要将该块封装在另一个JavaScript函数中。
此代码的整体思想是允许JRuby开发人员编写Ruby代码并在jxBrowser中执行此代码,而无需使用任何JavaScript。通过下载mdarray-sol GEM已经可以看到这方面的例子,或者去https://github.com/rbotafogo/mdarray-sol。在那里你可以看到JRuby使用d3.js的多个例子。
你能请使用callback()方法提供Java类的代码示例。 – Vladimir
我没有设法在此评论中添加代码示例,因此我将添加作为以下问题的答案... –