Passing data from Java to JavaScript

Hello there!

I’m new to Vaadin and trying to add the chart.js library to my application in order to display some fancy charts.

First tests with single JS files constructing the bar chart with static dummy data, which were included via UI.getCurrent().getPage().addJavaScript(…) in my View, worked pretty good so far.

Now I would like to query live data from the database and display them. Therefore I need to pass the data from my Java side to the JavaScript file, which then constructs the bar chart.
What is the best approach to achieve this?

In the docs I found the section about Polymer Templates. The documentation describes only the handling of databinding with HTML objects.
Can my intention be implemented with polymer templates?

Are there any sample code sources that show how external libraries (e.g. chart libraries) are included and used with dynamic data?

Famous Johannes Goebel created a Vaadin Add-On: ApexCharts.js
Maybe this is already enough charting for you.

https://vaadin.com/directory/component/apexchartsjs

Demo:

https://appreciated-collection.herokuapp.com/apexcharts/

For the Java->Javascript part you can have a look there.

For ChartJs there is a helper library implemented in Java which can output JSON Strings for the chart configuration: https://github.com/mdewilde/chart

Thank you for your answer.

The question related more to the general approach than to the use of a specific library. Depending on the use case I need a different library. For example Chart.js fits well to simple charts, but offers (without extensions; and currently I don’t know how to include a new npm module in the build process) no possibility to create a funnel chart, just like apexcharts. For this I would like use d3.js or another library.

For now, I solved my problem as follows:

According to the documentation https://vaadin.com/docs/v16/flow/creating-components/creating-components-overview.html I created a new component and added some JavaScript files (UI.getCurrent().getPage().addJavaScript(…)).
From the Java side, I called a init-function of the JavaScript file and passed the Component-instance, which allows to make calls from JavaScript to Java. https://vaadin.com/docs/v16/flow/element-api/client-server-rpc.html#clientcallable-annotation explains this pretty good.

I was not able to achieve the same result using polymer templates. Using that approach, I could make any calls from Java to JavaScript in order to pass the server reference. Also I had some issues figuring out, how to make a call from JavaScript to Java and returning some values. “EventHandler” does not allow you to return values. So for now, I will stick to the easy method mentioned above.