我可不是真正的編碼在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
我沒有設法在此評論中添加代碼示例,因此我將添加作爲以下問題的答案... –