Tornadofx: EventBus not work with child view

Created on 15 Feb 2018  路  4Comments  路  Source: edvin/tornadofx

when I define a subscription in a daughter view the subscription is not released.

object MyEvent : FXEvent()

class MainView : View("")

override val root = VBox () {
this += ChildView()
}

}

class ChildView : View("") {
init {
subscribe<MyEvent > {
// this not work, not fire after invoke fire() method from MainView
}
}

Thanks

Most helpful comment

This happens because you manually instantiate the ChildView. You must never instantiate a UI Component manually as it prevents it from taking part in important life cycle events. Either use inject, find, or add. Simply changing this += ChildView() to add<ChildView>() resolves the issue.

There are a number of other issues with your code, here is a cleaned up sample with best practices.

object MyEvent : FXEvent()

class MainView : View() {
    override val root = vbox {
        add<ChildView>()
        button("Fire").action { fire(MyEvent) }
    }

}

class ChildView : View() {
    override val root = label("Waiting...") {
        subscribe<MyEvent> {
            text = "Event was fired at ${LocalDateTime.now()}"
        }
    }
}

All 4 comments

This happens because you manually instantiate the ChildView. You must never instantiate a UI Component manually as it prevents it from taking part in important life cycle events. Either use inject, find, or add. Simply changing this += ChildView() to add<ChildView>() resolves the issue.

There are a number of other issues with your code, here is a cleaned up sample with best practices.

object MyEvent : FXEvent()

class MainView : View() {
    override val root = vbox {
        add<ChildView>()
        button("Fire").action { fire(MyEvent) }
    }

}

class ChildView : View() {
    override val root = label("Waiting...") {
        subscribe<MyEvent> {
            text = "Event was fired at ${LocalDateTime.now()}"
        }
    }
}

Thanks, that work for me, but how send params to ChildView?

I need pass viewmodel to ChildView and currently do it by constructor.

Read up on Scopes in the documentation. They allow you to do just this without requiring parameter passing.

Thanks Grant :) The other alternative is to change ChildView to a Fragment and pass parameters to find. Also well documented in the guide :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MairwunNx picture MairwunNx  路  8Comments

arslancharyev31 picture arslancharyev31  路  7Comments

jordaorodolfo picture jordaorodolfo  路  6Comments

vlipovetskii picture vlipovetskii  路  6Comments

pavan-p picture pavan-p  路  3Comments