在Vaadin 8中自动更新活页夹中相关计算属性的显示

时间:2017-03-26 08:14:35

标签: data-binding vaadin vaadin8

在Vaadin 8中使用Binder时,如果bean具有只读计算属性,其值来自另一个属性,如何让TextField自动更新派生计算的显示当驾驶财产的价值发生变化时会产生什么结果?

在以下示例中,当用户更改“出生年份”字段时,如何让“年龄”字段更新其计算?

enter image description here

Vaadin 8的完整工作示例。

package com.example.val;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.data.converter.StringToIntegerConverter;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

import javax.servlet.annotation.WebServlet;
import java.time.LocalDate;
import java.time.ZoneId;

/**
 * This UI is the application entry point. A UI may either represent a browser window
 * (or tab) or some part of a html page where a Vaadin application is embedded.
 * <p>
 * The UI is initialized using {@link #init(VaadinRequest)}. This method is intended to be
 * overridden to add component to the user interface and initialize non-component functionality.
 */
@Theme ( "mytheme" )
public class MyUI extends UI {

    Person person;
    Binder < Person > binder;

    @Override
    protected void init ( VaadinRequest vaadinRequest ) {
        // Data model
        this.person = new Person ( "Jean-Luc", 1955 );

        // Widgets
        final TextField nameField = new TextField ( "Type the person’s name here:" );
        final TextField yearOfBirthField = new TextField ( "Type the year of birth here:" );
        final TextField ageField = new TextField ( "Approximate age:" );
        ageField.setReadOnly ( true );
        final Label beanToString = new Label ( );

        // Binder
        this.binder = new Binder <> ( );
        binder.forField ( nameField )
                .bind ( Person:: getName, Person:: setName );
        binder.forField ( yearOfBirthField )
                .withConverter ( new StringToIntegerConverter ( "Input must be Integer" ) )
                .bind ( Person:: getYearOfBirth, Person:: setYearOfBirth );
        binder.forField ( ageField )
                .withConverter ( new StringToIntegerConverter ( "" ) )
                .bind ( Person:: getAge, null );
        binder.setBean ( this.person );

        final Button button = new Button ( "Save" );
        button.addClickListener ( event -> {
            if ( binder.validate ( ).isOk ( ) ) {
                // With `setBear`, the Person object is always up-to-date as long as there are no validation errors.
                // MyBackend.updatePersonInDatabase(person);
                beanToString.setValue ( this.person.toString ( ) );
            } else {  // Else bean flunks validation.
                beanToString.setValue ( "The Person bean has invalid state." );
            }
        } );


        this.setContent ( new VerticalLayout ( nameField, yearOfBirthField, ageField, button, beanToString ) );
    }

    @WebServlet ( urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true )
    @VaadinServletConfiguration ( ui = MyUI.class, productionMode = false )
    public static class MyUIServlet extends VaadinServlet {
    }
}

class Person {
    private Integer yearOfBirth;
    private String name;


    public Person ( String name_, Integer yearOfBirth_ ) {
        this.name = name_;
        this.yearOfBirth = yearOfBirth_;
    }

    public String getName ( ) {
        return name;
    }

    public void setName ( String name ) {
        this.name = name;
    }

    public Integer getYearOfBirth ( ) {
        return yearOfBirth;
    }

    public void setYearOfBirth ( Integer yearOfBirth ) {
        this.yearOfBirth = yearOfBirth;
    }

    // Read-only property 'age', calculated rather than stored.
    public Integer getAge ( ) {
        LocalDate today = LocalDate.now ( ZoneId.systemDefault ( ) );
        Integer years = ( today.getYear ( ) - this.yearOfBirth );
        return years;
    }

    @Override
    public String toString ( ) {
        return "Person{ " +
                "yearOfBirth=" + yearOfBirth +
                ", age='" + this.getAge ( ) + "'" +
                ", name='" + name + "'" +
                " }";
    }
}

2 个答案:

答案 0 :(得分:2)

我找到的最简单方法是以下列方式修改yearOfBirthField的绑定代码:

binder.forField(yearOfBirthField)
    .withConverter(new StringToIntegerConverter("Input must be Integer"))
    .bind(Person::getYearOfBirth, (Setter<Person, Integer>) (person1, integer) -> {
                person1.setYearOfBirth(integer);
                ageField.setValue(person1.getAge().toString());
            });

这有效地将yearOfBirthField绑定到yearOfBirth属性并更新person bean的age属性。 以任何方式更改person bean的成员,例如通过调用person.setYearOfBirth(1977)对字段没有立即影响。 Vaadin的更新机制只能朝一个方向发展。字段修改将传输到bean,但反之亦然。

修改

在Vaadin 8中,没有内置方法可以在bean属性发生变化时自动更新Field。当yearOfBirthField的值发生更改时,新值将传播到person bean,并且人员yearOfBirth成员将通过绑定自动更改。但是之后Vaadin没有获取bean的所有绑定字段的当前值。因此ageField未更新且未反映当前值。

因此,要使ageField显示更新后的值,您必须以编程方式更新ageField。您可以在绑定器上再次设置整个bean,这将导致所有getter被调用,但最简单的方法是在设置yearOfBirth之后设置ageField的值。这是在建议的setter绑定修改中完成的。

答案 1 :(得分:1)

显然,使用Binder API改变了行为,在快速浏览一下源代码之后,似乎不支持这样的刷新功能。话虽如此,Vaadin家伙considering就是这个案子......

我认为最干净/最安全的方法是在字段本身添加一个侦听器,而不是依赖于此 new 绑定API的某些行为。事实上,嗯......&#34; new&#34;,它可能会在即将发布的Vaadin版本中得到增强。更重要的是,UI字段的更新可能是即时的。

修改

再想一想,你可以做的最小的事情是在成功验证后重新读取bean(这与@Morfic通过再次设置bean的建议没有太大区别):

if (binder.validate().isOk()) {

  // Force update of the Fields...
  binder.readBean(binder.getBean());

  beanToString.setValue(person.toString());
} else {
  beanToString.setValue("The Person bean has invalid state.");
}