Class JsSnippets

java.lang.Object
com.vaadin.flow.js.JsSnippets

public final class JsSnippets extends Object
Hands out implementations of JsDefinition interfaces whose methods declare snippets: JavaScript that is not run when the method is called, but evaluated later on the client by what the returned value is passed to.

A snippet is not bound to an element, which is why the implementation comes from here rather than from Element.executeJs(Class). It holds no state, so one implementation can be kept in a constant and shared.

A snippet declares a function that a call of another definition then gets as an argument:

 @JsDefinition
 public interface LoggerJs extends Serializable {

     @JsExpression("console.log($0, value);")
     @JsFunctionParameterNames("value")
     JsFunction createLogger(String prefix);
 }

 @JsDefinition
 public interface ClickJs extends Serializable {

     @JsExpression("this.addEventListener('click', () => $0('clicked'));")
     void onClick(JsFunction handler);
 }

 static final LoggerJs LOGGER = JsSnippets.of(LoggerJs.class);

 button.getElement().executeJs(ClickJs.class)
         .onClick(LOGGER.createLogger("Button:"));
 
The build collects both declarations into the bundle, roughly as:
 // LoggerJs.createLogger: a snippet, evaluated with the captured arguments
 jsSnippets["<id>"] = function ($0) {
     return function (value) {
         console.log($0, value);
     };
 };
 // ClickJs.onClick: a call, run on the element it was obtained from
 jsDefinitions["<id>"] = async function ($0) {
     this.addEventListener('click', () => $0('clicked'));
 };
 
The server sends the browser only the two identifiers and the argument "Button:". The client calls the snippet function with "Button:" to get the logger, and runs onClick on the button with that logger as $0, so a click logs Button: clicked. Nothing is compiled from a string, which is what keeps this working under a content security policy that does not allow unsafe-eval.
Since:
25.4
See Also:
  • Method Details

    • of

      public static <T> T of(Class<T> definitionType)
      Gets an implementation of the given JavaScript definition, whose methods answer with the snippet they declare.
      Type Parameters:
      T - the JavaScript definition type
      Parameters:
      definitionType - the JavaScript definition, not null
      Returns:
      an implementation of the interface, not null
      Throws:
      IllegalArgumentException - if the type is not an interface, is not annotated with JsDefinition, or has a method that does not declare a snippet