Closed leastbad closed 5 years ago
That's expected. Each controller instance initialize()
s once and only once when its element first connect()
s, but may connect()
and disconnect()
multiple times if the element is reconnected to the DOM. See https://stimulusjs.org/reference/lifecycle-callbacks.
Here's a quick demo to help illustrate: https://codepen.io/javan/pen/dwZPmo?editors=1011
Thank you so much for the insanely fast reply.
For what it's worth, I couldn't find anything in the docs or closed issues that explains this. It might be a good candidate for inclusion in the next round of documentation errata.
For what it's worth, I couldn't find anything in the docs or closed issues that explains this.
Did you see https://stimulusjs.org/handbook/managing-state#lifecycle-callbacks-explained and / or https://stimulusjs.org/reference/lifecycle-callbacks?
Yes, and I just read them again, now, to be sure.
There’s nothing that explicitly spells out that initialize fires once per instantiation. The addition of a short note might save future noobs the confusion I experienced this morning. 🤓
There’s nothing that explicitly spells out that initialize fires once per instantiation
I understand what we see differently. What I’m trying to explain is that to a newcomer, your use of the word Once instead of the term “Once per instance/occurrence” is just ambiguous enough to be confusing.
The one thing I have is the perspective of an experienced developer doing work with the library for the first time. If you don’t think it’s worth explaining further, no sweat. I really appreciate your explanation regardless.
I am seeing Stimulus fire the initialize event twice when I include two instances of a controller in a document. I am under the strong impression that I should see two connect events but only one initialize event per page load.
This happens even without Turbolinks in the picture:
https://codepen.io/pjforde1978/pen/aPVzbR?editors=1011
Apologies if I'm doing it wrong. It seems unlikely that nobody else would have noticed this, and yet I am unable to come up with a simpler example.