Where is JavaScript.getCurrent().addFunction(String, JavaScriptFunction) in

In Vaadin 8 I made heavy use of the addFunction method on JavaScript.getCurrent() but it’s no longer available in Flow. What’s the recommended replacement?

Hello. You can declare a [@ClientCallable]
(https://vaadin.com/docs/v14/flow/element-api/client-server-rpc.html#calling-server-side-methods-from-the-client) method in the Java class

@ClientCallable
public String getGreeting(String name) {
    return "Hello " + name;
}

and invoke it from client-side code as

getServerGreeting() {
  let greetingPromise = this.$server.getGreeting("JavaScript");
  greetingPromise.then(greeting => console.log(greeting));
}

Yes, I’m aware of that but it won’t work for my use case. In Vaadin 8 I could add JS functions from any component and have the callback initiated on the server. I have XML stored in a DB that is styled into HTML using XSL. The HTML invokes the JS functions. Now I have to rewrite everything to use Vaadin components which I didn’t have to do in Vaadin 8.

In that case you can add the functions using executeJs (since a JS function is just another property of the element).

Button b = new Button("Say hello");
b.getElement().executeJs("this.sayHello = function() { alert('HELLO'); };");
b.addClickListener(ev->{b.getElement().callJsFunction("sayHello");});
add(b);

If you want global functions (which you just can call as sayHello() from JS code), you can add them as properties of window:

getElement().executeJs("window.sayHello = function() { alert('HELLO'); };");

I need the JS to callback to the server. What you’re proposing is a server to client call.

Yes, I got it backwards.

Client to server communication in Vaadin Flow is accomplished either through ClientCallable methods or event handling. The ClientCallable mechanism requires an annotated server-side method on some component, which doesn’t fit your description. The other approach is firing a customEvent from JavaScript and have it handled in the server side (here you can use different event names, and add the listeners dynamically; events can also have arbitrary payload, see https://vaadin.com/docs/v14/flow/creating-components/tutorial-extending-component.html and particularly the first comment from Stephan Uebe at the bottom)

It’s also possible to devise some “compatibility layer” by using the executeJs approach, so that it wraps the event dispatch as a JS function call with the same syntax as you were using with Vaadin 8.