I’m trying out Stimulus for use with the htmx.org js framework to load partials. I’d like to test this just using Stimulus from the cdn. I have a simple hello example with an index.php page, on this page there is an htmx get which loads a partial on page load as an ajax call. The partial being loaded is named component.html. I’ve created a controller in /src/controllers/hello_controller.js. (not sure if that is correct path?) index.php initializes Stimulus ok and the partial loads ok but the controller does not appear to execute. It works if everything is on index.php. No idea what is not setup ok at this point. Anyone have experience with how to set this up with Stimulus for partial loads?
So, you have Stimulus loaded on your index page, but when you insert content, any
data-controller attributes embedded in the new content don’t seem to be registering? eg. you don’t see their
connect methods firing?
I’m not familiar with the development environment you’re using, but can you confirm that you are either using something like webpack to roll up all of your Stimulus controllers into a bundle, or if you’re using
script tags, that you have loaded all of the controllers you plan to use? Stimulus can’t process controllers that aren’t registered before use.
If you can post your code on Github, perhaps we’d be able to help more.
Thanks for the response. I did determine that the problem is that the controllers won’t get registered when the content with a data-controller is loaded. I’m not using a bundler but what I’ve done is similar to what I think you were getting at. I put all my controller code into a script file which loads with initial page load. In that file I’ve wrapped the application.register(…) calls in a function with a switch statement inside it. So when the partial content loads I embed a function call in the response as inline script tags passing the name of the component that is being loaded and the registration occurs and it all works. Maybe not the most elegant approach but works for me and I only register controllers as needed.