Search code examples
javascriptjavavaadin

Vaadin custom component - keep access to javascript variable


I'm writing a custom component based on leaflet.browser.print and I have a question on how to keep access to some objects I initialise in javascript.

As you can see in the code below I instantiate the class LBrowserPrintImport and execute a script that initializes the variable bp. This variable should be used in the java function print() again. But I don't find any information on how to store it.

Do you have any ideas?

Here is my code so far:

@NpmPackage(value = "leaflet.browser.print", version = "2.0.2")
@JsModule("leaflet.browser.print/dist/leaflet.browser.print.min.js")
public class LBrowserPrintImport extends Component {

    private static final long serialVersionUID = 1L;
    
    public LBrowserPrintImport(
            final LMap map,
            final LBackendOptions backendOptions
            ) {
        super();
        getElement().executeJs("let bp = L.browserPrint($0, $1);", "map", "parameters");
        // How to store bp here?
    }
    
    public void print() {
        getElement().executeJs("bp.print(L.BrowserPrint.Mode.Landscape());");
    }
}

Solution

  • You could attach the variable to some element like the component's root element, or global object, such as the window: executeJs("window.bp = L.browserPrint($0, $1);