How to interact with the middleware from custom JavaScript component?

Hi!

I am quite new to CUBA. I have a custom jQuery component with several declared functions that I would like to call from the CUBA middleware at runtime.
In tutorial on how to integrate custom JavaScript library there is only example on how to call server side from the client, but I need other way round interaction.

Please advise if there are any examples that may help.

Cheers
Andrey

Hi,

If you check this sample: Using a JavaScript library - CUBA Platform. Developer’s Manual You will see that changes from Server to JS component are delivered using getState() property of ServerComponent to onStateChange callback of JS Connector. So, you just set data to State and then JS component will receive them with server response in onStateChange callback. Also, you can use com.vaadin.ui.AbstractJavaScriptComponent#callFunction method from ServerComponent to trigger JS connector method after response.

I’ve created a small demo GitHub - cuba-labs/js-slider: JavaScript JQuery Slider integration

Here we define new method of SliderServerComponent that will trigger JS function:


@JavaScript({"slider-connector.js", "jquery-ui.min.js"})
@StyleSheet({"jquery-ui.min.css"})
public class SliderServerComponent extends AbstractJavaScriptComponent {
    // ...

    // Call JS Component from Server with parameters
    public void showNotification(String greeting) {
        callFunction("showNotification", greeting);
    }
}

The function is registered in connector.js file:


com_company_demo_web_toolkit_ui_slider_SliderServerComponent = function() {
    // ...
    
    // Here we receive call from Server
    connector.showNotification = function (greeting) {
        window.alert(greeting + connector.getState().values);
    }
};

In a screen we simply call this API method:


slider.showNotification("Value is: ");

And JS component will show browser Alert.

See also this Vaadin docs: Integrating JavaScript Components and Extensions | Client-Server Integration | Framework | Vaadin 8 Docs

1 Like

I think there is something important missing in the example above. Since I can’t edit the response, I will add it here:

com_company_demo_web_toolkit_ui_slider_SliderServerComponent = function() {
    var connector = this;
    // ....
    
    // Here we receive call from Server
    connector.showNotification = function (greeting) {
        window.alert(greeting + connector.getState().values);
    }
};

Notice the var connector = this; - without it, it won’t work.