Class JsFunction

java.lang.Object
com.vaadin.flow.dom.JsFunction
All Implemented Interfaces:
JsSnippet, Serializable

public final class JsFunction extends Object implements JsSnippet
A JavaScript function value with captured parameters that can be passed to Element.executeJs(String, Object...) as a parameter and reified on the client as an actual callable JS function.

The body is a JavaScript function body. Captures are referenced positionally as $0, $1, … (the same naming convention as executeJs parameters). Additional named runtime arguments can be declared with withArguments(String...): the materialised function then accepts them positionally and the body references them by name. On the client the value materialises as a function with the captures pre-bound, so the parent executeJs can invoke it as $N(arg1, arg2, ...) without ever concatenating user-supplied JavaScript with framework boilerplate.

Captures may be any value accepted as a parameter to executeJs, including Element (attached elements arrive as DOM nodes, detached ones as null) and nested JsFunction instances. Capture types are validated when the value is created.

Inside the body, this is whatever the caller of the materialised function chooses (i.e. it follows normal JavaScript call semantics – not the host element). To use the host element from within the body, pass it as a capture.

A function created with of(String, Object...) is compiled in the browser from its body, which a content security policy that does not allow unsafe-eval forbids. A function can instead be declared as a JsSnippet by a method of a JsDefinition interface, whose JavaScript the build collects into the bundle, so the browser is sent the identifier of the function and the captures rather than a body:

 @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);
 }

 button.getElement().executeJs(ClickJs.class)
         .onClick(JsSnippets.of(LoggerJs.class).createLogger("Button:"));
 
Such a function has no body on the server, and its runtime arguments are declared by JsFunctionParameterNames rather than with withArguments(String...).
Since:
25.2
Author:
Vaadin Ltd
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    boolean
    equals(@Nullable Object obj)
    Checks whether the given object is a function that runs the same JavaScript with the same captures: the same function of the bundle, or the same body, together with the same argument names and captures.
    Deprecated, for removal: This API element is subject to removal in a future version.
    The names are part of the JavaScript of the function, which is what the client compiles from them.
    Deprecated, for removal: This API element is subject to removal in a future version.
    The body is what the client compiles the function from, and a function declared by a JsDefinition interface, which is not compiled from a string, has none.
    List<@Nullable Object>
    The captured values, in declaration order.
    @Nullable JsCall
    Gets the call of a JsDefinition method that declared this function, which names the function of the bundle it runs.
    int
     
    static JsFunction
    of(String body, @Nullable Object... captures)
    Creates a JavaScript function value with the given body and captured parameters.
    static JsFunction
    Creates the function that a call of a method of a JsDefinition interface declares, which the build collects into the bundle.
    withArguments(String... argumentNames)
    Returns a copy of this function that declares the given names as positional runtime arguments.

    Methods inherited from class java.lang.Object

    clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • of

      public static JsFunction of(String body, @Nullable Object... captures)
      Creates a JavaScript function value with the given body and captured parameters.

      The function is compiled in the browser from its body, which a content security policy without unsafe-eval does not allow, so the CspMode of the application reports or refuses it. A function declared by a method of a JsDefinition interface is collected into the bundle instead, and the browser is sent only its identifier and the captures. The class documentation shows how to declare one.

      Parameters:
      body - the JavaScript function body, with captures referenced as $0, $1, …; not null
      captures - the values to capture; each must be a type supported as a parameter to Element.executeJs(String, Object...)
      Returns:
      a new JsFunction instance
      Throws:
      IllegalArgumentException - if any capture has a type that cannot be sent to the client
      CspViolationException - in the CspMode.STRICT Content Security Policy mode
    • ofDeclaredCall

      public static JsFunction ofDeclaredCall(JsCall call)
      Creates the function that a call of a method of a JsDefinition interface declares, which the build collects into the bundle.

      For internal use only. May be renamed or removed in a future release. Application code should not call this method. Instead, obtain the function by calling the relevant method on the implementation returned by JsSnippets.of(Class).

      Parameters:
      call - the call of a method that returns a function, not null
      Returns:
      a new JsFunction instance
      Throws:
      IllegalArgumentException - if the called method does not declare a JsSnippet
      RuntimeException - if any argument of the call cannot be encoded to be sent to the client
      Since:
      25.4
    • getDeclaredCall

      public @Nullable JsCall getDeclaredCall()
      Gets the call of a JsDefinition method that declared this function, which names the function of the bundle it runs.

      For internal use only. May be renamed or removed in a future release.

      Returns:
      the declaring call, or null for a function created from a body with of(String, Object...)
      Since:
      25.4
    • withArguments

      public JsFunction withArguments(String... argumentNames)
      Returns a copy of this function that declares the given names as positional runtime arguments. The materialised function accepts these arguments at call time, and the body references them by name.

      Example:

       JsFunction alerter = JsFunction.of("alert(message);")
               .withArguments("message");
       element.executeJs("$0('Hello')", alerter);
       
      Parameters:
      argumentNames - the names of runtime arguments, in positional order; each must be a valid JavaScript identifier
      Returns:
      a new JsFunction with the given argument names
      Throws:
      IllegalStateException - if argument names have already been set on this instance, or if this function is declared by a JsDefinition interface, which declares its arguments with JsFunctionParameterNames
    • getBody

      @Deprecated(since="25.4", forRemoval=true) public String getBody()
      Deprecated, for removal: This API element is subject to removal in a future version.
      The body is what the client compiles the function from, and a function declared by a JsDefinition interface, which is not compiled from a string, has none. The body of a function created with of(String, Object...) is the one passed to it.
      The JavaScript function body.
      Returns:
      the body string
      Throws:
      IllegalStateException - if this function is declared by a JsDefinition interface, whose JavaScript is in the bundle rather than in the function
    • getCaptures

      public List<@Nullable Object> getCaptures()
      The captured values, in declaration order. For a function declared by a JsDefinition interface, these are the arguments of the call that declared it.
      Returns:
      an unmodifiable list of captures
    • getArgumentNames

      @Deprecated(since="25.4", forRemoval=true) public List<String> getArgumentNames()
      Deprecated, for removal: This API element is subject to removal in a future version.
      The names are part of the JavaScript of the function, which is what the client compiles from them. They are the ones passed to withArguments(String...) or declared with JsFunctionParameterNames.
      The names of the runtime arguments declared via withArguments(String...), or with JsFunctionParameterNames for a function declared by a JsDefinition interface, in positional order.
      Returns:
      an unmodifiable list of argument names; empty if none were declared
    • equals

      public boolean equals(@Nullable Object obj)
      Checks whether the given object is a function that runs the same JavaScript with the same captures: the same function of the bundle, or the same body, together with the same argument names and captures. A captured array is compared by its current contents.
      Overrides:
      equals in class Object
      Parameters:
      obj - the object to compare with
      Returns:
      true if the object is an equal function
      Since:
      25.4
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object