Reputation: 4908
We are investigating Stimulus.js for use with our Rails6 app and keep hitting conceptual walls in moving our thinking from jQuery to Stimulus.
For example:
On one part of the page we have a button and when that button is clicked we want to load content into a div on another part of the page. In jQuery this is simple - respond to click
event, load in the part from the rails backend into that div.
In Stimulus, how to do this? It looks like everything needs to be in one big controller so that the button can see the 'target div'. So essentially we are writing 'page' controllers, which seems a lot of overhead. Also, it messes up the way we are breaking down the page into partials because now those partials need to share a Stimulus controller.
Upvotes: 6
Views: 4511
Reputation: 1785
You definitely don't need to be writing 'page' controllers. The idea is that you write smaller controllers for interactive elements. If you post more about your use case perhaps we can help you split apart your controllers. You are correct though that the controller's element must contain any element registered as a target. Just remember you can access elements outside that context (e.g. in a completely different part of the page) using regular Javascript (in other words document.getElementById
can give you access just as easily as using Stimulus targets)
To answer your question though, you can do something like this:
show() {
fetch("/path/to/partial")
.then((res) => res.text())
.then((html) => {
const fragment = document
.createRange()
.createContextualFragment(html);
this.element.appendChild(fragment);
// OR document.getElementById("testy_element").appendChild(fragment)
});
}
What this does is fetch an HTML response from the Rails server and insert it inside of the main controller's element (this.element
). For example:
<div class="container" data-controller="test">
<button data-action="test#show">Do the Thing</button>
<!-- partial would appear here -->
</div>
Upvotes: 1