SvelteOnRails::TurboStream
Setup
Please setup the turbo-rails gem and follow the chapter Come alive with Turbo Streams, which mainly is:
bundle add turbo-rails
rails turbo:install
make sure that import "@hotwired/turbo-rails" is on your application.js and set the view helper <%= turbo_stream_from 'authenticated' if current_user %> to your view.
If a channel (e.g.: authenticated) is active and you have an HTML element with a HTML-ID (e.g.: svelte-on-rails-stream-actions-box), you can test it by:
Turbo::StreamsChannel.send(
"broadcast_append_to",
'authenticated',
target: 'svelte-on-rails-stream-actions-box',
content: "<div>Turbo-Streams are working!</div>"
)
When this works you are good to go.
Configs
Check the regarding keys and their commends on the config file. From there, you just need:
turbo_stream:
target_html_id: 'svelte-on-rails-stream-actions-box'
channel: 'public'
Minimal Usage Example
And call this by:
SvelteOnRails::TurboStream.dispatch
What it does
- A Stimulus controller is pushed to all subscribers of the configured channel.
- You can override the channel name by passing
channelto the method.
- You can override the channel name by passing
Usage Example, more detailed
If you want to fire a event on a specific element within the component, you do not need addComponentStreamListener. Just do something like:
<script>
function logStreamMessage(event) {
console.log(event.detail.message)
}
</script>
<button class="counter-button" onclick="{logStreamMessage}">Show Contents</button>
within the svelte component.
Then, call it by:
SvelteOnRails::TurboStream.dispatch(
channel: 'my-custom-stream',
component: '/javascript/components/TurboStreamsChannel',
selector: '.counter-button',
event: 'click',
event_detail: { message: "Greetings from Server: äöü🤣🌴🌍漢字" }
)
The #dispatch_by_selector does not go over the component, it searches for any matching selector just on the whole document and fires the given event there.