将javascript回调作为java方法参数传递

时间:2017-01-09 13:55:01

标签: javascript java gwt

在我的GWT应用程序中,我有第三方反应模块 我需要将成功/失败回调从javascript传递到java,我将用数据填充它

JS PART

function() {
        var reactCallback = {
            success: function() {
                console.log('success!');
            },
            error: function() {
                console.log('error!');
            }
        };
        window.reactRpcService(reactCallback);
    }

JAVA GWT PART

 public static native void reactRPCService(ReactRPCServiceAccessor reactRpc)/*-{
    $wnd.reactRpcService = function(callback){
        reactRpc.@com.myproject.ReactRPCServiceAccessor::dispatchRPCRequest(???)(callback);
    }
}-*/;


    private void dispatchRPCRequest(???) {

    }

计划是调用java GWT RPC函数规范化数据并通过回调将其发送回javascript 我曾经想过将它作为JavascriptObject在Java中传递但不知道它是否是一种好方法

任何想法的人?

1 个答案:

答案 0 :(得分:0)

实际上我发现根据javadocs的JavascriptObject可以是passed back into JSNI from Java becomes the original object, and can be accessed in JavaScript as expected.

所以在我的原生函数中,我添加了像这样的签名

public static native void setupNativeRactRPCServiceCalls(ReactRPCServiceAccessor reactRpc)/*-{
    $wnd.reactRpcService = function(callback){
        reactRpc.@com.myproject.ReactRPCServiceAccessor::dispatchRPCRequest(Lcom/google/gwt/core/client/JavaScriptObject;)(callback);
    }
}-*/;

 private void dispatchRPCRequest(final JavaScriptObject callback ) {
...retrieve JSON data
}

然后从服务器检索数据后,我已将其传递回javascript

   public static native void reactDataRedirector(JavaScriptObject callbackObject, String jsonData)/*-{
        callbackObject.success(jsonData);
}-*/;