by 023984398 · 5y ago · 0 comments
Turbo seemed more connected with existing models, and so I chose a Stimulus controller instead. But maybe I just don't know Turbo as much yet.
1. Replace the `output` target with a Turbo frame. 2. Add a value to the `data-controller` div with a `preview-url`: https://stimulus.hotwire.dev/reference/values 3. Change the `Rails.ajax` call with `let url = URL.new(this.previewUrlValue); url.searchParams.append('body', this.tweetTarget.value; this.outputTarget.src = url.toString();` 4. Change the `preview` action to render HTML with the same frame.
Now you have an automatic refreshing frame with less code.
You can also have a hidden form submission that does this from the existing controller so you don't need to specify the URL.
For example, you can add a hidden submit button like
form.submit 'preview', data: { composer_target: 'submit' }, hidden: true
Instead of a stimulus target, you wrap your preview area in a turbo frame <turbo-frame id="output">
...
</turbo-frame>
In your (ruby) controller you can re-use the existing controller action: def create
@post = Post.new(post_attributes)
preview && return if params[:commit] == 'preview'
...
end
Do the turbo junk in a private method for the preview: private
def preview
render turbo_stream: turbo_stream.replace(
'output', partial: "posts/preview", locals: { post: @post }
end
end
Your stimulus controller now just does this: preview() {
this.submitTarget.click();
}
I'm not sure which I prefer!But as for the AJAX call, I still think it's quite simple solution that most will instantly understand (and that's a good thing).
this would be very useful, as there are not many comparative articles that really help you choose one approach over another. a number of years ago, i went through a couple rounds of turbo vs. ujs vs. websockets vs. custom js vs. something other library i don't remember atm, to try to figure out the best option for the app i was working on. lots of articles talk about the strengths of a library compared to others, but almost none walk through an example (or two) with enough depth to show those differences explicitly.