JsInterop Function Callback

420 views
Skip to first unread message

Cristian Rinaldi

unread,
Sep 25, 2015, 5:33:33 PM9/25/15
to GWT Contributors
Hey:
  
   I'm using JsInterop to map some JS APIs.
What is the best way to map a callback to receive multiple parameters?

For example, a jQuery click handler: function (event, params)

In Java could be:

Function fn =  new Function() {
   
@Override
   
public Object call(Event event, Object... params) {
      setVisible
(!visible);
     
return null;            
}


but then is complicated to manipulate the "Object []", there is a more direct way?

Cristiano

unread,
Sep 30, 2015, 2:09:53 AM9/30/15
to GWT Contributors
I think you could try to use a class annotated with @JsType, both for return type and arguments...

if you pass in jQuery an object like this json:
{ "key1": "value1", "key2": "value2"}

and your code is 
public MyObject call(Event event, MyObject param1, MyObject param2) { ... }

with a MyObject class like this :

@JsType
public class MyObject {
     public String key1;
     public String key2;
}

it should work.
The concept is that you'll rather have to manage potential runtime issue! No compile time type checking will prevent you to invoke the function from jquery with invalid type of the parameter...

I'm still exploring JsInterop so please correct me if I am wrong ;)

Cristiano

Goktug Gokdogan

unread,
Sep 30, 2015, 3:39:54 PM9/30/15
to google-web-toolkit-contributors
There are no var args support yet to ease this so you need to multiple arguments as Cristiano suggested.

However you can do some bridging to keep look/work nicer.

interface VarArgFunction {
  public Object call(Event event, Object..params) {
}

class VarArgConverterFunction {

     VarArgFunction delegate;

     VarArgConverterFunction(VarArgFunction delegate) { this.delegate = delegate; }

    
@Override
    
public Object call(Event event, Object param1, Object param2, Object param3) {
      return delegate.call(event, new Object[] { param1, param2, param3 );
    }  
}

You can also do similar bridging in javascript in a more generic way.

function(e) {
   delegateFunction.call(e, Array.prototype.slice.call(arguments, 1));
}

PS: Note that in the first solution params.length will be incorrect and might be better better if you prune null params while the second javascript baed solution should be ok;

--
You received this message because you are subscribed to the Google Groups "GWT Contributors" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-web-toolkit-contributors/006c06dd-9c64-4dbe-a3b9-b08be4d2f506%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages