Firstly, the topic name might not be fully descriptive and I’m open for suggestions.
The overall setup
HeadController. This controller does some async stuff such as calling external HTTP based APIs, interacting with other preloaded third-party scripts/objects and manipulating some global state. All this is initiated within
HeadController.initialize() and happens through a promise then chain.
The site’s body contains several elements which each have another Stimulus controller attached to them, though the number is irrelevant with regards to the underlying problem. In this case it’s instances of the same controller class, though this should be irrelevant as well. Let’s call this controller
DoStuffController.connect() needs to, well, do stuff, but depends on a fully completed flow within
HeadController.initialize(). With the current setup,
DoStuffController.connect() are sometimes called before the actions within
HeadController.initialize() are done and thus before
HeadController.initialize() is done.
Somehow halting the flow until
initialize() is done is not an option.
I’m wondering how you would go about solving this issue. As I gather from the documentation there is no built-in way to neither monitor the current state of a Stimulus controller, nor to create flow related dependencies between them, nor to trigger/monitor one controller from another and as such no built-in way to achieve what I need? Correct me if I am wrong.
I did have a quick read through issue #35
Attempt a a solution:
I am sure there is a number of patterns which could be utilized to solved this such as:
A) The Observer pattern could be used although
- this would couple the individual controllers slightly more tight than one might want
- subscriptions taking place after subject’s completion will have no effect as there is neither history nor state and no way to monitor it if there were.
B) The Publisher/subscriber pattern solves caveat 1 of the Observer pattern but not caveat 2.
There might be (combinations of) other patterns which could be used that I am not aware of but as a stopgap solution I went with a bastardized version of the Observer with internal state tracking within the subject. This way I can trigger a notify on the subscriber if it subscribes after flow completion. I’m am using
this.application.getControllerForElementAndIdentifier(..) from within the subscriber which is part of the coupling related problem.
Neither approach nor solution is close to being elegant and I will more than likely regret it later on as the application grows.
I would very much like to hear your thoughts on this as well as and alternative solutions.