2

js中的任意函数对象是否可以传递给Java端,所以java可以调用那个js对象?(回调)

例如,(访问是一个已经注册调用Java函数的函数)

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

有没有什么很棒的技术可以处理java中的匿名回调函数?

4

1 回答 1

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);
于 2016-11-15T00:47:21.590 回答