2.6.6. Using Events

Let’s consider the use of events. We will add handling of a graph item click to the screen created in Screen Controller. Open the screen controller and inject the chart. In order to show a notification, inject the Notifications bean into the screen controller.

@Inject
private Notifications notifications;

@Inject
private SerialChart chart;

Then add a listener at the bottom of the onInit method. When a chart receives data from DataProvider, the getDataItemNN() method should be used to get the item clicked. In this example, the SerialChart component is bound to the data container, so another method should be used: getEntityNN():

@Subscribe
private void onInit(InitEvent event) {
    chart.addGraphItemClickListener(graphItemClickEvent ->
            notifications.create()
                    .withCaption(itemClickEventInfo(graphItemClickEvent))
                    .withContentMode(ContentMode.HTML)
                    .show());
}

private String itemClickEventInfo(Chart.GraphItemClickEvent event) {
    CountryGrowth countryGrowth = (CountryGrowth) event.getEntityNN();
    return String.format("GDP grow in %s (%s): %.1f%%",
            countryGrowth.getCountry(),
            event.getGraphId().substring(5),
            "graph2014".equals(event.getGraphId()) ? countryGrowth.getYear2014() : countryGrowth.getYear2015());
}

To see the results, rebuild the project using RunRestart application server and log in to the system. Open the screen and click one of the columns.

chart with event
Figure 31. Chart that handles graph item click event