How to pass a GWT method as a parameter into a Javascript function?

这一生的挚爱 提交于 2019-12-13 04:02:01

问题


Overview

  • There is a GWT method called: private void handleError()
  • There is a JSNI Javascript function called: private native void registerErrorHandler()
  • The native javascript function calls another function from a third party Javascript library: foo.attachEvent("EventName", handlerReference);

Functionality

I need to pass the GWT method as a function parameter into the foo.attachEvent() function, i tried several approaches:

foo.attachEvent("Error", registerErrorHandler); -> TypeMismatchException

foo.attachEvent("Error", this.@package.foo::registerErrorHandler()); -> TypeMismatchException

var handler = this.@package.foo::registerErrorHandler()();
foo.attachEvent("Error", handler);

-> TypeMismatchException

Plain Javascript

When I write this in plain Javascript, it's working:

function handleError() {
    alert("Error");
}
function registerErrorHandler() {
    var event = "Error";
    var handler = handleError;

    foo.attachEvent (event, handler);
}

How can I implement that into GWT? I am having a lot of problems completely understanding the Javascript - Java Objects conversion. I understand the handleError function reference as a JavaScriptObject, but I am not able to get it working with that information.


回答1:


you code needs to look like this: (there are only one time braces, therefore the function is not executed...)

var handler = this.@package.foo::registerErrorHandler();
foo.attachEvent("Error", handler);

but what you also want to do is wrap your function in the $entry function so that your uncaught exception handler will work:

var handler = this.@package.foo::registerErrorHandler();
foo.attachEvent("Error", $entry(handler));

What you can always do is build a js function that directly calls your gwt function:

var that = this;
var handler = function(){
    that.@package.foo::registerErrorHandler()();
};
foo.attachEvent("Error", $entry(handler));


来源:https://stackoverflow.com/questions/11427970/how-to-pass-a-gwt-method-as-a-parameter-into-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!