Polymer: Client-To-Server Data Transfer

Hello, all,

I’m working on a custom web component. I need to retrieve data from the client-side code by calling a server-side method. Example:

Server-side:

public class MyCustomComponent extends PolymerTemplate<MyCustomComponent.Model> {

...

public void getData() {

	getElement().callFunction("getData", "");
}

Client-side:

getData() {
	
	// Package data
}

What I don’t understand is how to get that packaged data back to the server-side code.

Polymer’s two-way binding and the TemplateModel came to mind, but I haven’t been able to get that working:

Client-side:

static get properties() {
	
	return {
	
		data: {
			type: String,
			notify: true
		}
	}
}

...

getData() {

	// Package data.
	this.data = packagedData
}

Server-side:

public interface Model extends TemplateModel {
	
	void setData(String data);
	
	String getData();
}

I’m missing a concept. Any help would be appreciated.

Thanks!

Bryan

Hi,

One way to do it would be to publish a method from the server and call it from the client, e.g.

@ClientCallable
public void setData(String data) {
...
}

on the client side, use this.$server.setData("foo");.

With Vaadin 14 you also have the option to get a return value from executeJS

getElement().callJsFunction("getData")
            .then(String.class, data -> {
				System.out.println("Got "+data);
            });

More details in https://vaadin.com/docs/v14/flow/element-api/client-server-rpc.html

Thanks for the quick reply, Artur.

This works. I’m getting client-side data in my server-side code, but the process appears to be asynchronous (my server-side code continues to execute before the client-side data is returned).

Is there a way around this in Vaadin 13? It looks like this asynchronous issue is resolved in Vaadin 14.

Bryan

Hi, there is no way to get around that when you access “the other side” (client from server or server from client) then it is asynchronous. The Vaadin 14 method is also asynchronous as you provide a callback which is invoked later, when the return value is available. What Vaadin 14 does is that it makes it easier to connect the request to the response.

If you know that the @ClientCallable will be invoked and you want to wait for it, you need to restructure the rest of the code so that it is called from the @ClientCallbale method

Thanks again, Artur. Much appreciated!