#839·stimulus

Newly inserted elements can't call previously instantiated controller methods

Author: simmerzCreated May 16, 2025Updated May 16, 2025

I have a hello controller:

javascript
import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  say() {
    console.log('I exist!')
  }
}

And an existence controller (because I don't have a TurboStream event to hook on to):

javascript
import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  connect() {
    this.dispatch('added')
  }

  remove() {
    this.dispatch('removed')
    this.element.remove()
  }
}

If I have html like this:

xml
<div data-controller="hello">
  <div id="replaceme">I'm about to be replaced by a turbo stream</div>
</div>

And I replace replaceme with:

xml
<div data-controller="existence" data-action="existence:added->hello#say">
I've been replaced
</div>

Nothing gets placed on the console. If I include hello as follows:

xml
<div data-controller="hello existence" data-action="existence:added->hello#say">
I've been replaced
</div>

then the hello controller gets instantiated when the element is rendered and it works fine.