One way to manage individual callback anonymous functions is by using a key for reference, similar to how jsonp operates at times.
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;
}
//Ensuring preservation of array index positions and resetting the array when empty
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
}
}
Java:
@org.xwalk.core.JavascriptInterface
public String TestCallback(String someData, String onSuccess, String onError){
xwalk.evaluateJavascript("getCallback(" + onSuccess + ")('success');", null);
}
Using this with JavaScript:
var onSuccess = registerCallback(function(r) {
console.log(r);
});
TestCallback('lalala', onSuccess, null);