我的主修课是这样设置的:
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()对象返回
发布于 2018-08-09 07:18:55
这是Scopes的一个很好的用例。作用域将控制器和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不能被框架实例化,所以您必须像我前面所展示的那样手动地将其中一个实例化到范围中。
class PollContext(path: String) : ViewModel() {
    val pathProperty = SimpleStringProperty(path)
    var path by pathProperty
    val currentDataProperty = SimpleStringProperty()
    var currentData by currentDataProperty
}发布于 2018-08-09 07:22:09
你可以这样做:
主应用程序
class MyApp: App(MainView::class)MainView
class MainView : View() {
    override val root = hbox {
        add(FileView("C:\\passedTestFile.txt"))
    }
}FileView
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)
    }
}FileController
class FileController: Controller() {
    val pathFile : String by param()
}控制器使用by param()通过参数接收路径,视图通过构造函数参数期望该变量,并在注入控制器时使用它( inject委托具有可选的params参数)。在使用此视图(在MainView中)时,只剩下在实例创建时传递文件路径的内容。
结果是:

无论如何,我将创建3层而不是2层,经典的模型-视图-控制器(或任何派生层)层,并将文件路径存储在模型中。
https://stackoverflow.com/questions/51757883
复制相似问题