Stimulus re-connect even with data-turbo-permanent?

I have a div that is marked as data-turbo-permanent and it is also attached to a stimulus controller.

When navigation occurs, the content of the div is correctly preserved. However, I am seeing disconnect and connect events firing from the Stimulus controller.

Two questions:

  1. Is this the desired behavior? If so, I could totally see the reasoning (e.g. the element is removed from the dom and re-inserted), just wanted to confirm.

  2. Has anyone found a way to override this? I have some side effects in my connect function (fetching data) that I do not want to duplicate.

Thanks,

Evan

Have you tried an initialize method instead of connect? That might answer your second question.

Good suggestion!

From the documentation, I was under the impression that initialize could not guarantee that Stimulus is attached to the dom. (e.g. “Once, when the controller is first instantiated” vs “Anytime the controller is connected to the DOM”) However, I was able to swap them out without issue.

However, I am not totally sure this is the “best” solution. I have some clean-up logic I would like to implement in disconnect (freeing resources, etc.). I would like this to be a “true” disconnect, i.e. when we’re navigating to a page without the permanent element, vs just the flicker of the element in and out of the dom.

initialize run once each time a new DOM element with a controller is initailized. Initialized is then followed by the connect method. Disconnect is called when that dom element is removed from the page, and then connect is called one more when the same dom element is later restored (e.g. turbo restoring from cache).

If you only want code to be called initially once per controller instance, initialize is the right method. If you want code to be called every time an element is add (or restored) to the DOM, then connect is the correct method.

1 Like