Stimulus Discourse

Connect callback might be called before full element content has been added to the DOM

#1

I’ve found that when web pages load slowly, the connect callback might be called before all the content of the element to which the controller has been connected has been added to the DOM.

As a result, you can’t reliable use the connect callback to set the initial state of your interface elements. For example, in the example below the callback can’t be used reliably to hide all except the first tab in a tabbed interface because not all panelTargets are guaranteed to be available when tabs#connect is called:

<section data-controller="tabs">
  <nav>
    <a data-action="click->tabs#show" data-target="tabs.tab">[…]</a>
    <a data-action="click->tabs#show" data-target="tabs.tab">[…]</a>
    <a data-action="click->tabs#show" data-target="tabs.tab">[…]</a>
  </nav>
  <ul>
    <li data-target="tabs.panel">[…]</li>
    <li data-target="tabs.panel">[…]</li>
    <li data-target="tabs.panel">[…]</li>
  </ul>
<section>

What would be the most appropriate way to delay the controller from connecting to the element until all its children are available in the DOM?

0 Likes

#2

What version of Stimulus are you using? This issue should be fixed as of version 1.1.0.

2 Likes

#3

Thank you, turns out the app was indeed still running an older version of Stimulus.

1 Like