Stimulus: initialize vs connect

Created on 29 Jan 2018  路  4Comments  路  Source: hotwired/stimulus

How do the initialize() and connect() differs in use?

Most helpful comment

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().

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MrHubble picture MrHubble  路  3Comments

pherris picture pherris  路  3Comments

kud picture kud  路  4Comments

jenkijo picture jenkijo  路  3Comments

tiagocassio picture tiagocassio  路  3Comments