Table of contents
1.
Introduction
1.1.
Attribute
1.2.
Property
1.3.
Using Attributes vs. Properties: Differences
2.
Listening to User Events Using the Element API
2.1.
Data Access From Events
3.
Remote Procedure Calls
3.1.
Calling Client-Side Methods From the Server
3.1.1.
callJsFunction Method
3.1.2.
executeJs Method
3.2.
Calling Server-Side Methods From the Client
3.2.1.
@ClientCallable Annotation
4.
Retrieving User Input Using the Element API
5.
Dynamic Styling Using the Element API
5.1.
Using classLists and classNames
5.2.
Using the Style Object 
6.
Frequently Asked Questions
6.1.
What is API?
6.2.
What do you mean by dynamic styling?
6.3.
How to determine whether to use property or attribute?
6.4.
Is Vaadin a JavaScript framework?
6.5.
Vaadin is it scalable?
7.
Conclusion
Last Updated: Mar 27, 2024

Element API

Author dhananjay
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article we are going to learn about the Element API and its variations using Vaadin.

Vaadin is a web Framework that is open source and  has built-in support for both Java script and AJAX. By using Google Web Toolkit, you may also incorporate outside functionality onto it. Vaadin saves developers time because it produces rich content in the browser devoid of the use of any markup files

Element API

A portion of an element can be updated and questioned using the Element API. Server-side elements' property and attribute values can be modified using the Element API.

Attribute

The primary purpose of attributes is to first configure elements.

Values for attributes are always kept as strings.

Example: Adding attributes to the element's nameField.

Element nameField = ElementFactory.createInput();
nameField.setAttribute("id", "nameField");
nameField.setAttribute("placeholder", "Rohan");
nameField.setAttribute("autofocus", "");
You can also try this code with Online Java Compiler
Run Code


Example: The same example as the one before, but in HTML form.

<input id="nameField" placeholder="Rohan" autofocus>

Property

  • Changing an element's parameters dynamically after initialization is the major usage of properties.
     
  • Any JavaScript value may be utilised in the browser as a property value.
     
  • The setProperty() function comes in a variety of iterations that let you set a property's value as a String, boolean, double, or JsonValue.
     

For illustration, set the property value to a double.

Element element = ElementFactory.createInput();
element.setProperty("value", "42.2");
You can also try this code with Online Java Compiler
Run Code


The getProperty() method can also be used in several ways to retrieve a property's value as a String, boolean, double, or JsonValue.

The value is converted if you retrieve a property's value as a different type from the one you used to set it using JavaScript type coercion rules. For instance, if a property is set to be a non-empty String and retrieved as a boolean, it returns true.

Recommended Topic, procedure call in compiler design

Using Attributes vs. Properties: Differences

Use characteristics and properties with caution:

1. A similar-sounding trait or property can frequently be used to achieve the same result, and both are effective.
 

2. However, in some circumstances:

  • only one of them functions, or
     
  • The property has effect after initialization, and the attribute is only taken into account when the element is initialised.
     

Listening to User Events Using the Element API

User Events Using the Element API

You can use the addEventListener() method provided by the Element API to listen to any browser event.

Example: Making a click event using the addEventListener() function.

Element helloButton = ElementFactory
        .createButton("Say hello");
helloButton.addEventListener("click", e -> {
    Element response = ElementFactory
            .createDiv("Hello!");
    getElement().appendChild(response);
});
getElement().appendChild(helloButton);
You can also try this code with Online Java Compiler
Run Code


The event is sent to the server for processing when the "Say hello" button is clicked in the browser, and a new "Hello!" element is also added to the DOM.

Data Access From Events

By adding the necessary event data to the DomListenerRegistration that the addEventListener() method returns, you can obtain further details about the element or user interaction.

As an illustration, define the necessary event data using the addEventData() method.

helloButton.addEventListener("click", this::handleClick)
    .addEventData("event.shiftKey")
    .addEventData("element.offsetWidth");
private void handleClick(DomEvent event) {
    JsonObject eventData = event.getEventData();
    boolean shiftKey = eventData
            .getBoolean("event.shiftKey");
    double width = eventData
            .getNumber("element.offsetWidth");

    String text = "Shift " + (shiftKey ? "down" : "up");
    text += " on button whose width is " + width + "px";

    Element response = ElementFactory.createDiv(text);
    getElement().appendChild(response);
}
You can also try this code with Online Java Compiler
Run Code

 

1. The client sends the requested event data values as a JSON object.
 

2. The event.getEventData() method in the listener can be used to get the event data.
 

3. Make sure to employ:

  • based on the data type, the appropriate getter;
     
  • the same keys that were given to the addEventData() function as parameters.
     

Remote Procedure Calls

Remote Procedure Calls

RPCs, or remote procedure calls, are a mechanism to run programmes or subroutines on another system or in a different address space.

RPC calls from the server to the client and vice versa are supported by Vaadin Flow to handle server-client communication.

Calling Client-Side Methods From the Server

By using the Element API, you can run client-side methods from the server.

callJsFunction Method

You can run a client-side component function from the server side using the callJsFunction() method. The name of the function to call and the arguments to give to the function are the two parameters that the method accepts.

The function's arguments must be of a type that the communication mechanism can handle. String, Boolean, Integer, Double, JsonValue, Element, and Component are the supported types.

Example: Calling the clearSelection() function using the callJsFunction() method.

public void clearSelection() {
    getElement().callJsFunction("clearSelection");
}

public void setExpanded(Component component) {
    getElement().callJsFunction("expand",
            component.getElement());
}
You can also try this code with Online Java Compiler
Run Code


executeJs Method

The executeJs() method can also be used to synchronously run JavaScript on the server. In addition to the callJsFunction() method, you can use this one.

The JavaScript expression to call and the parameters to send to the expression are the two inputs that the executeJs() function accepts. Keep in mind that the specified parameters are accessible as variables with names like $0, $1, and so on.

The expression must receive arguments of a type that the communication method supports. String, Integer, Double, Boolean, and Element are the kinds that are supported.

Using the executeJs() method as an example.

public void clearSelection() {
    getElement().callJsFunction("clearSelection");
}
public void setExpanded(Component component) {
    getElement().callJsFunction("expand",
            component.getElement());
}
You can also try this code with Online Java Compiler
Run Code


Calling Server-Side Methods From the Client

@ClientCallable Annotation

You can use the @ClientCallable annotation to call a server-side method from the client. It identifies a Component subclass method that can be used by the client to call the method. Notation for $server.serverMethodName(args). This relates to the corresponding element in client-side Polymer template code, therefore this is the calling convention. $server.serverMethodName(args).

If the server's return type is void, the client-side method returns null instead of a Promise, which will be resolved asynchronously with the server's return value. You can use Promise.then to wait for the outcome (). The await keyword can also be used to wait for the outcome of an async function.

Example: Using this.$server.getGreeting() to call a server-side method and await the result.

async getServerGreeting() {
  let greeting = await this.$server.getGreeting("JavaScript");
  console.log(greeting);
}
You can also try this code with Online Javascript Compiler
Run Code


Retrieving User Input Using the Element API

Retrieving User Input Using the Element API

In this part, we show you how to retrieve user input using the Element API. In our example, a text input field for the user's name has been added.

1. Make a text input element.

Example: Adding a placeholder attribute to a textInput element.

Element textInput = ElementFactory.createInput();
textInput.setAttribute("placeholder",
        "Please enter your name");
You can also try this code with Online Java Compiler
Run Code

 

2. Every time the value changes in the browser, ask the client to update the server-side input element to send the updated value to the server.

Example: Updating the value of the text input element using the addPropertyChangeListener() function and a NO-OP listener.

textInput.addPropertyChangeListener("value", "change", e -> {});a
You can also try this code with Online Java Compiler
Run Code

 

3. Utilize the Element to get the synchronised characteristics. API getProperty().

An example would be to retrieve the property value using the textInput.getProperty("value") method.

button.addEventListener("click", e -> {
    String responseText = "Hello " +
            textInput.getProperty("value");
    Element response = ElementFactory
            .createDiv(responseText);
    getElement().appendChild(response);
});
You can also try this code with Online Java Compiler
Run Code


Dynamic Styling Using the Element API

Dynamic Styling Using the Element API

The Element API allows you to style elements with inline styles or dynamic class names.

Two methods in the Element API make styling easier:

  • Get the list of CSS class names used for the element using getClassList().
     
  • To control element inline styles, use getStyle() to retrieve the style instance.

Using classLists and classNames

To obtain a list of the CSS class names applied to the element, use the getClassList() function. Class names can be added or subtracted from the set that is returned.

CSS style guidelines

.blue {
  background: blue;
  color: white;
}


For instance, changing the class names of an element on the fly using the getClassList() method.

button.setText("Change to blue");
button.addEventListener("click",
    e -> button.getClassList().add("blue"));
You can also try this code with Online Java Compiler
Run Code


Using the Style Object 

The Style object returned by the element can be used to add and remove inline styles for an element. the getStyle() function. Style property names can be formatted in kebab case or camel case, for instance, backgroundColor (for example, background-color).

Use the getStyle() method, for instance, to style inline text dynamically.

Element input = ElementFactory.createInput();
button.setText("Change to the entered value");
button.addEventListener("click",
    e -> button.getStyle().set("background",
            input.getProperty("value")));
You can also try this code with Online Java Compiler
Run Code


Frequently Asked Questions

What is API?

Application Programming Interface is referred to as API. Any software with a specific function is referred to as an application when discussing APIs. Interface can be compared to a service agreement between two programmes. This agreement specifies the requests and responses that the two parties will use to communicate.

What do you mean by dynamic styling?

style. colour = "red"; you can dynamically apply the style change. Here is a function that, when given the element's id, changes an element's colour to red. To apply a style to an element, use setAttribute(key, value).

How to determine whether to use property or attribute?

To determine whether a feature should be configured using a property or an attribute, you should always consult the appropriate documentation for the element you are using.

Is Vaadin a JavaScript framework?

An open-source Java framework for creating web applications is called Vaadin Flow. You can create an app entirely using UI elements without ever touching HTML or JavaScript.

Vaadin is it scalable?

Vaadin apps scale effectively. Errors are possible with any framework, as with anything else. However, it's simple to develop applications with Vaadin that not only scale well but also look amazing and operate excellently, making your users happy, by adhering to traditional Java best practices.

Conclusion

In this article, we learned about Vaadin, the Element API, and the various variations that may be used with it. Using element API, we have learned about user input and dynamix styling as well as characteristics, properties, and the differences between them.

To learn more about the Vaadin please refer to the following articles:

Vaadin-Creating First Application

Vaadin-Core Elements

Vaadin-User Interface Components

To learn more about DSA, competitive coding and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

thank you

 

Please upvote our blog to help other ninjas grow.

Happy Learning

Live masterclass