js中的任意函数对象是否可以传递到java端,以便java可以调用该js对象?(回拨)
例如,(access是一个已经注册用来调用java函数的函数)

access(function(blabla){
    ...
});

有什么好的技术可以处理java中的匿名回调函数吗?

最佳答案

您只需要某种密钥来引用您的单个回调匿名函数。我认为有时候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);

10-08 06:47