How to call a JavaScript function from GWT with jsInterop?

1.8k views Asked by At

I tried the exampels in the docu https://docs.google.com/document/d/10fmlEYIHcyead_4R1S5wKGs1t2I7Fnp_PaNaa7XTEk0/edit# in the section @JsFunction but it gives only ideas to call java function from javascript.

I have a javascript file included in my GWT app with the following code:

var client = new Circuit.Client({
    client_id: '78cafde2f6854ad5ad80a67c532687bc',
    scope: 'READ_USER_PROFILE,READ_CONVERSATIONS',
    domain: 'circuitsandbox.net'
});

function startLogon() {
    client.logon()
      .then(user => console.log('Logged on as ' + user.displayName))
      .then(client.addEventListener('itemAdded', item => console.log('itemAdded event received:', item)))
      .then(client.getConversations)
      .then(conversations => {
         console.log('Retrieved ' + conversations.length + ' conversations');
    return client.addTextItem(conversations[0].convId, 'Hello World');
       })
      .then(item => console.log('Msg sent on ' + (new Date(item.creationTime)).toString()))
      .catch(console.error);
}

Now i want to call the function 'startLogon()' - my be with a wrapper - from my app using jsInterop annotations. I tried the two following examples without any success:

Implement Javascript Function Callback with GWT JsInterop

JsInterop wrapping a javascript function property

I have to say, that my JavaScript knowledge is very bad.

Can someone give me a code example? Many thanks in advance!

1

There are 1 answers

0
Ignacio Baca On

Add this static method to any class.

@JsMethod(namespace = GLOBAL)
public static native void startLogon();

This will work, although you cannot do anything with the returned promise. If you want to use the returned promise I recommend adding elemental2 and use Promise startLogon() instead so you can consume it like this:

startLogon().then(
    success -> { console.log("success", success); return null; },
    failure -> { console.log("failure", failure); return null; });