Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

disconnect/connect not firing after data-controller is changed #204

Closed
richardkmiller opened this issue Nov 10, 2018 · 2 comments
Closed

Comments

@richardkmiller
Copy link

Hello! I did a personal deep dive on Stimulus yesterday and I'm really liking it.

FWIW, it appears that removing and re-adding the data-controller attribute on an existing element did not cause the connect and disconnect methods to be called. Am I missing anything here?

The docs say this should be among the reasons for disconnect() to be called, i.e. "the element’s data-controller attribute is removed or modified".

I started with the Glitch demo and defined connect() and disconnect() in hello_controller.js:

  connect() {
    console.log("Hello!")
  }
  disconnect() {
    console.log("Goodbye!")
  }

I added the following body to index.html:

<body>
  <div id="hello" data-controller="hello"></div>
  <button>Replace controller</button>
</body>

I added the following to index.js to trigger the change (delete and re-add) on the data-controller attribute:

document.querySelectorAll('button')[0].addEventListener('click', function() {
  console.log("Replacing data-controller attribute");
  document.getElementById('hello').setAttribute('data-controller', '');
  document.getElementById('hello').setAttribute('data-controller', 'hello');
});

In the console I see "Hello!" when the script first loads, but I don't see it when I click the "Replace controller" button like I would expect.

Here's the Glitch link if it helps:
https://glitch.com/edit/#!/zealous-vole-1?path=src/index.js:13:0

Thanks!

@javan
Copy link
Contributor

javan commented Nov 10, 2018

Synchronously removing and restoring an attribute is the same as not changing it as far as the DOM is concerned (more on that, if you're interested).

If you defer restoring the attribute, you'll see the results you expect:

document.getElementById('hello').setAttribute('data-controller', '');
setTimeout(function() {
  document.getElementById('hello').setAttribute('data-controller', 'hello');
})

https://glitch.com/edit/#!/denim-engineer?path=src/index.js:13:4
https://denim-engineer.glitch.me/

@javan javan closed this as completed Nov 10, 2018
@richardkmiller
Copy link
Author

@javan Got it! That's helpful for understanding what's going on here. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants