有没有办法在绑定器的特定字段上添加类似值变更监听器的方式?

huangapple go评论158阅读模式
英文:

Is there a way to add a something like a value change listener on specific field in binder?

问题

我需要在文本字段(TextField)和组合框(ComboBox)中的更改时添加反应。

Binder 是在 Vaadin 中处理数据绑定的一种方便方式。

我不能使用 textField.addValueChangeListener(...),因为它在绑定的模型中设置新值之前就已经被调用了。

是否有一种方法可以在绑定器(binder)的特定字段上添加类似于值更改监听器的东西?

我可以使用 binder.addValueChangeListener(),但它会在每个绑定字段更改时触发,而且我不能轻松区分它们。

理想情况下,会是这样的:

binder.forField(specificTextField)
    .withConverter(...)
    .withValidator(...)
    .bind(Person::getName, Person::setName)
    .addValueChangeListener(...); // 不存在的功能
英文:

I need to add a reaction in my interface on changes in TextField and ComboBox.

Binder is a convinient way for handling data binding in Vaadin.

I can't use on textField.addValueChangeListener(...) as it is called before new value is set in binded model.

Is there a way to add a something like a value change listener on specific field in binder?

I can use binder.addValueChangeListener() but it is fired on every bound field changes and I can't easily tell them apart.

Ideally, it would be something like that:

binder.forField(specificTextField)
    .withConverter(...)
    .withValidator(...)
    .bind(Person::getName, Person::setName)
    .addValueChangeListener(...); // nonexistent functional

答案1

得分: 2

关于是否有一种方法可以为单个绑定本身添加值更改监听器的问题的答案是否定的。我同意这可能是Flow API的一个很酷和有用的补充。请继续在他们的GitHub上提交一个问题。

然而,正如你自己注意到的,有Binder::addValueChangeListener方法,而且确实有一种方法可以区分它们。被接受的事件监听器有一种方法可以获取触发更改事件的HasValue(即绑定的输入字段),它还可以访问旧值和新值。

TextField tf = new TextField();
ComboBox cb = new ComboBox();
// todo: 绑定字段

binder.addValueChangeListener(valueChangeListener -> {
    if (valueChangeListener.getHasValue().equals(tf)) {
        // tf的值已更改
    } else if (valueChangeListener.getHasValue().equals(cb)) {
        // cb的值已更改
    }
}
英文:

The answer to the question whether there is a way to add a value change listener to a single Binding itself is no there is not. I agree this could be a cool and useful addition to the Flow API. Please go ahead and write an issue in their github

However, as you noticed yourself, there is the method Binder::addValueChangeListener, and there is a way to tell them apart. The accepted eventListener has a way to get the HasValue (a.k.a. bound input field) that fired the change event. it also has access to both the old and the new value.

TextField tf = new TextField();
ComboBox cb = new ComboBox();
// todo: binding of fields

binder.addValueChangeListener(valueChangeListener -> {
    if(valueChangeListener.getHasValue().equals(tf)){
        // tf value changed
    } else if(valueChangeListener.getHasValue().equals(cb)) {
        // cb value changed
    }
}

huangapple
  • 本文由 发表于 2020年7月29日 01:57:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63140117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定