Interface JsSnippet

All Superinterfaces:
Serializable
All Known Subinterfaces:
CompiledLitTemplate
All Known Implementing Classes:
DomEventData, DomEventFilter, JsFunction

public interface JsSnippet extends Serializable
JavaScript that is declared on the server and evaluated later on the client, by whatever it is passed to.

A method of a JsDefinition interface that returns a snippet type does not run anything. Called on the implementation that JsSnippets.of(java.lang.Class<T>) hands out, it answers with a value that names the function the build generated from its JsExpression and carries the arguments of the call, which the expression references as $0, $1, …. The value is passed on, for instance as an argument of a method of a definition obtained from Element.executeJs(Class). When the client decodes the argument, it gets a function with those arguments bound, and the expression runs when the invoker calls that function, as described for JsFunctionParameterNames. Nothing is compiled from a string in the browser, so a snippet passed that way works under a content security policy that does not allow unsafe-eval. Passed to Element.executeJs(String, Object...) it works as well, but the expression of that call is itself compiled from a string.

A snippet has no identity on the client and no lifetime. Passing the same snippet to several invocations creates its function once per invocation, and each of them gets a function of its own, so there is nothing to cache and nothing to release.

JsFunction is the snippet type for a function that whoever it is passed to calls with arguments of its own, which JsFunctionParameterNames names. DomEventFilter and DomEventData are snippet types that a DOM event listener runs for every event.

A component or an application can declare a snippet type of its own for what it invokes on the client, as an interface that extends this one and declares no instance methods. It names what the snippet is for, so an API can accept only snippets of that kind, and it can declare the parameters every snippet of it is called with by annotating the type with JsFunctionParameterNames:

 @JsFunctionParameterNames({ "html", "item" })
 public interface ItemTemplate extends JsSnippet {
 }

 @JsDefinition
 public interface OrderTemplates extends Serializable {
     @JsExpression("return html`<b>${$0}: ${item.status}</b>`;")
     ItemTemplate status(String label);
 }
 
JsSnippets.of(Class) implements the type, and a snippet of it is sent to the client like a JsFunction that a JsDefinition interface declares: as the function the client calls with those parameters.
Since:
25.4
See Also: