Skip to content

Newly inserted elements can't call previously instantiated controller methods #839

@simmerz

Description

@simmerz

I have a hello controller:

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):

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:

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

And I replace replaceme with:

<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:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions