Use ClickHandler with native Javascript object?

In Javascript, I create an SVG form and add a click handler to it as follows:

var rect = document.createElementNS('http://www.w3.org/2000/svg','rect'); rect.addEventListener('click', myClickHandler, false); 

This works great. I am trying to make a Rect overlay class in GWT. If possible, I would just like to do something like this:

 public class SVGRect extends JavaScriptObject { public native void addClickHandler(ClickHandler handler) /*-{ addEventListener('click', handler, false); }-*/; } 

Thus, I can pass the β€œnormal” GWT handler to this class and use it externally like any other regular GWT interface element. I'm not sure how to associate a ClickHandler object with the original implementation of a javascript object?

thanks

+4
source share
1 answer

Since you need ClickEvent to switch to ClickHandler.onClick , and getting it from JavaScript creates a problem (AFAICT) - I would go with a slightly different, more "general" approach:

Create a simple callback interface:

 public interface Callback { void execute(); } 

Then you can pass it directly and call it like this:

 public native void addClickHandler(Callback callback) /*-{ addEventListener('click', function() { callback.@path.to.your.package.Callback ::execute()(); }, false); }-*/; 

Or create an intermediate step:

 public void addClickHandler(Callback callback) { _addClickHandler(getCallback(callback)); } private native void _addClickHandler(JavaScriptObject callback) /*-{ addEventListener('click', callback, false); }-*/; // This can be moved to a better place private native static JavaScriptObject getCallback(Callback callback) /*-{ return function() { callback.@path.to.your.package.Callback ::execute()(); }; }-*/; 

And of course you would use it like this:

 SVGRect svg = getMeSVGRect(); svg.addClickHandler(new Callback() { @Override public void execute() { // Do some stuff } }); 

Personally, I prefer the second solution - while this is more code, I like to keep my own / JSNI methods private (unless it's an overlay object or something like that), and the code is more readable and less error prone (no need to use funky syntax for calling Java functions from within native / JSNI code).

+3
source

Source: https://habr.com/ru/post/1299294/


All Articles