是否可以将js中的任意函数对象传递给Java端,因此java可以调用该js对象? (回调)
例如,(访问是已经注册以调用Java函数的函数)
access(function(blabla){
...
});
有没有什么好的技术可以处理java中的匿名回调函数?
答案 0 :(得分:3)
您只需要某种键来引用您的单个回调匿名函数。我认为这也是有时使用jsonp的方式。
使用Javascript:
var callbacks = [];
function registerCallback(callback)
{
callbacks.push(callback);
return callbacks.length - 1;
}
function getCallback(index)
{
var callback = callbacks[index];
callbacks[index] = null;
TryGCCallbacks();
return callbacks;
}
//The array index positions must be preserved, but when it's empty, we should restart the array so it doesn't grow forever
function TryGCCallbacks()
{
var isCallbackRemaining = false;
for (var i = 0; i < callbacks.length; i++)
{
if (callbacks[i] == null) {
continue;
}
isCallbackRemaining = true;
break;
}
if (isCallbackRemaining == false)
{
callbacks = []; //reset
}
}
爪哇:
@org.xwalk.core.JavascriptInterface
public String TestCallback(String someData, String onSuccess, String onError){
xwalk.evaluateJavascript("getCallback(" + onSuccess + ")('success');", null);
}
使用Javascript:
var onSuccess = registerCallback(function(r) {
console.log(r);
});
TestCallback('lalala', onSuccess, null);