Can not call Java from JavaScript

I’m trying to implement a method to call Java from JavaScript as described here.
https://vaadin.com/docs/latest/flow/element-api/client-server-rpc

Calling the JavaScript method greet(name) from Java works OK.
But when debugging my JavaScript code which should call the Java method this.$server.testCallBack();, $server is undefined.

Using Vaadin 19.

I think some things have changed here between Vaadin versions as some of the documentation refers to this.$server and others to element.$server.

Code

Java function:

@Override
protected void onAttach(AttachEvent attachEvent) {
	UI.getCurrent().getPage().executeJs("greet($0)", "from Java");
}
	
@ClientCallable
public void testCallBack() {
	logger.info("Test");
}

JavaScript function:

window.greet = function greet(name) {
    alert("Hi, " + name);
    this.$server.testCallBack();
}

From the documentation:
It marks a method in a Component subclass that can be called from the client side using the element.$server.serverMethodName(args) notation. In client-side Polymer template code, this refers to the corresponding element so that the calling convention is this.$server.serverMethodName(args).

In your case:

window.greet = function greet(name) {
    alert("Hi, " + name);
    this.$server.testCallBack();
}

this does not mean anything (maybe it’s the ‘window’). It’s not really easy even with the documentation.

You can use a webcomponent like PolymerElement or LitElement and this.$server will work or with plain javascript you need to use element.$server like here:
https://github.com/jcgueriaud1/sortable-layout/blob/master/sortable-layout/src/main/resources/META-INF/resources/frontend/sortableConnector.js

Or in your case:


@Override
protected void onAttach(AttachEvent attachEvent) {
	UI.getCurrent().getPage().executeJs("greet($0, $1)", "from Java", getElement());
}
	
@ClientCallable
public void testCallBack() {
	logger.info("Test");
}

JavaScript function:


window.greet = function greet(name, element) {
    alert("Hi, " + name);
    element.$server.testCallBack();
}

I didn’t try it but it should work.

Thanks Jean-Christophe!

Indeed getElement() and element.$server where the missing pieces of the puzzle which were unclear to me from the documentation… now works perfectly!