[英]Passing variable to class constructor by inject() in java/kotlin
我的主课是这样设置的:
class MyView : View() {
val controller: PollController by inject()
etc
}
我想传递一个变量(例如路径文件的字符串)
class PollController : Controller() {
val currentData = SimpleStringProperty()
val stopped = SimpleBooleanProperty(true)
val scheduledService = object : ScheduledService<DataResult>() {
init {
period = Duration.seconds(1.0)
}
override fun createTask() : Task<DataResult> = FetchDataTask()
}
fun start() {
scheduledService.restart()
stopped.value = false
}
inner class FetchDataTask : Task<DataResult>() {
override fun call() : DataResult {
return DataResult(SimpleStringProperty(File(**path**).readText()))
}
override fun succeeded() {
this@PollController.currentData.value = value.data.value // Here is the value of the test file
}
}
}
[DataResult只是一个SimpleStringProperty数据类]
以便PollController类中的函数可以引用路径文件。 我不知道注射的工作原理。 @Inject始终保持红色,添加构造函数会抛出Controller()对象返回
这是Scope的好用例。 作用域将Controllers和ViewModels隔离开,以便您可以使用不同版本的资源使用不同的作用域。 如果还添加ViewModel来保存上下文,则可以执行以下操作:
class MyView : View() {
val pc1: PollController by inject(Scope(PollContext("somePath")))
val pc2: PollController by inject(Scope(PollContext("someOtherPath")))
}
现在,将上下文对象添加到Controller中,以便您可以从控制器实例中的任何函数访问它。
class PollController : Controller() {
val context : PollContext by inject()
}
上下文对象可以包含输入/输出变量。 在此示例中,它以输入路径作为参数。 请注意,框架无法实例化这种ViewModel,因此您必须像上面显示的那样手动将其中一个放入Scope。
class PollContext(path: String) : ViewModel() {
val pathProperty = SimpleStringProperty(path)
var path by pathProperty
val currentDataProperty = SimpleStringProperty()
var currentData by currentDataProperty
}
您可以执行以下操作:
主应用
class MyApp: App(MainView::class)
主视图
class MainView : View() {
override val root = hbox {
add(FileView("C:\\passedTestFile.txt"))
}
}
档案检视
class FileView(filePath: String = "C:\\test.txt") : View() {
private val controller : FileController by inject(params = mapOf("pathFile" to filePath))
override val root = hbox {
label(controller.pathFile)
}
}
文件控制器
class FileController: Controller() {
val pathFile : String by param()
}
控制器使用by param()
通过参数来赋值路径,视图期望通过构造函数参数来使用此变量,并在注入控制器时使用它( inject
委托具有可选的params
参数)。 使用此视图(在MainView
)时,剩下的唯一一件事就是在实例创建时传递文件路径。
最终得到:
但是,这项工作有效,我将创建3层而不是两层,即经典的model-view-controller(或任何派生)层,并将文件路径存储在模型中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.