That’s mostly true. Both controllers are initialized synchronously because they appear in the DOM at the same time. Here’s a very simplified of what Stimulus does:
[ ParentController, MultiWordChildController ].forEach(controllerConstructor => {
const controller = new controllerConstructor()
this.application.controllers.push(controller)
controller.initialize()
controller.connect()
})
Your ParentController
instance can’t find the MultiWordChildController
instance because the forEach
loop hasn’t gotten to its next cycle yet.
Switching the registration order would happen to fix it:
const application = Stimulus.Application.start()
-application.register('parent', ParentController)
application.register('multi-word-child', MultiWordChildController)
+application.register('parent', ParentController)
I don’t recommend relying on that as a long term fix though since it’s not documented behavior and could change.
Instead, defer accessing the child controller:
initialize() {
setTimeout(() => {
console.log(this.getChild(this.childTarget))
})
}
Or even
initialize() {
Promise.resolve().then(() => {
console.log(this.getChild(this.childTarget))
})
}