繁体   English   中英

Tornadofx - 在 ViewModel 中保持全局访问的属性?

[英]Tornadofx - Keeping globally accessed properties in a ViewModel?

推理:

大家好。 我正在构建一个进化模拟器作为个人项目。 我在文本字段上设置了一些参数,例如模拟的速度和“有机体”的数量。 这些将被应用程序的多个组件访问。 因为我还想对一些参数使用验证,所以我设置了一个 ViewModel,如下所示:

class ParametersModel: ViewModel() {
    // These properties would likely be DoubleProperty, but for simplicity lets pretend they are strings
    val simulationSpeed = bind { SimpleStringProperty() }
    val organismsGenerated = bind { SimpleStringProperty() }
}

...然后对文本字段执行验证测试:

val model = ParametersModel()
textfield(model.simulationSpeed).required()

这很好用,但问题是我将 model 属性定义为绑定到空的SimpleDoubleProperty ,这是多余的,因为我从不提交此 model (程序应始终在键入更改时读取更改)。 同时,我不能简单地定义 model 属性:

class ParametersModel: ViewModel() {
    val simulationSpeed = SimpleStringProperty()
    val organismsGenerated = SimpleStringProperty()
}

因为然后我收到有关验证的错误:

The addValidator extension can only be used on inputs that are already bound bidirectionally to a property in a Viewmodel. Use validator.addValidator() instead or make the property's bean field point to a ViewModel.

我可以采取的另一个选择是制作一个名为 GlobalProperties 之类的 class,它可以保留我的属性以及 ValidationContext。 然后我可以使用validationContext.addValidator添加验证器并传递文本字段。 但在这一点上,我觉得我只是在编写一个 ViewModel 等价物。

问题:

ViewModel 是保持由文本字段设置的“全局”访问参数的正确方法吗? 如果是这样,有没有办法不必将 model 属性设置为空属性的绑定,因为我不需要提交任何东西?

通常你会使用带有某种 model 的ViewModel 然后您可以使用ViewModel来处理用户输入,它存储用户输入的当前 state,并且支持 model 只会在ViewModel提交时更新,假设验证通过(这似乎与您声称您“不永远需要提交任何东西”)。

像这样的东西:

class Parameters {
    val simulationSpeedProperty = SimpleStringProperty(...)
    var simulationSpeed by simulationSpeedProperty

    val organismsGeneratedProperty = SimpleStringProperty(...)
    var organismsGenerated by organismsGeneratedProperty
}

class ParametersModel(parameters: Parameters): ItemViewModel<Parameters>(parameters) {
    val simulationSpeed = bind(Parameters::simulationSpeedProperty)
    val organismsGenerated = bind(Parameters::organismsGeneratedProperty)
}

然后,您可以确定支持ParametersParametersModel中始终包含有效值(当然假设它是使用有效值初始化的)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM