How do the initialize() and connect() differs in use?
Stimulus calls initialize() once per controller, and connect() every time the controller is connected to the DOM.
For example, say you have:
<div id="hello" data-controller="hello"></div>
Stimulus calls the corresponding controller鈥檚 initialize() method first, followed by connect().
If you then remove the element from the document:
const element = document.getElementById("hello")
element.remove()
Stimulus calls the controller鈥檚 disconnect() method.
Now, if you add the element back to the document:
document.body.appendChild(element)
Stimulus calls the controller鈥檚 connect() method again, but does not call initialize().
Thanks @sstephenson for the clarification. It would be great this info see in Handbook. Pardon me if I overlooked.
Yes, I agree! I鈥檓 working on getting it into the handbook right now :)
Here's the link to the section in the handbook: Lifecycle Callbacks Explained.
Most helpful comment
Stimulus calls
initialize()once per controller, andconnect()every time the controller is connected to the DOM.For example, say you have:
Stimulus calls the corresponding controller鈥檚
initialize()method first, followed byconnect().If you then remove the element from the document:
Stimulus calls the controller鈥檚
disconnect()method.Now, if you add the element back to the document:
Stimulus calls the controller鈥檚
connect()method again, but does not callinitialize().