Vaadin Flow: Difference between Component and Element

olivmir :

In Vaadin Flow additional to Components there are now Elements.

In the javadoc for Element is said:

A Component is a higher level abstraction of an Element or a hierarchy of Elements.

What does this mean practically? What is done on this higher level and when Elements and when Components are used?

Leif Åstrand :

As a practical example, let's consider the HTML tag <input>. You can create a server-side Element instance that gives you an <input> in the browser as Element myElement = new Element("input").

Furthermore, let's say you want to configure the placeholder text of the element, e.g. <input placeholder="Enter your name here">. Using the Element API, this is myElement.setAttribute("placeholder", "Enter your name here").

As a final example, you also add a listener that forwards value change events to the server. You'd also need to configure which parts of the browser event to send to the server and access that value in the listener: myElement.addEventListener("change", event -> System.out.println("New value: " + event.getEventData("element.value")).addEventData("element.value");.

You could build your entire application in this way, but it wouldn't be convenient. You want to have a class that knows that the tag name is input without typing out the string every time. You want a setPlaceholder method instead of using the generic setAttribute and remembering the name of the attribute. Finally, you'd want a way of adding a value change listener where the new value is available as event.getValue().

This is exactly where Component enters the picture. It lets you to create an Input class that extends Component and provides a Java API for exactly these features. Under the hood, the Input component would use the Element API, but hide it as implementation details that the user of the Input class wouldn't have to know about.

Furthermore, a component can also be based on other components instead of directly using Element. This is typically how you create the components that make up e.g. views in your application.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86459&siteId=1