Last active
August 25, 2021 17:14
-
-
Save cbilgili/c78f8e89515cd807f817f35d721570a6 to your computer and use it in GitHub Desktop.
Simple Chat with Hotwire Turbo Stimulusjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= turbo_frame_tag "new_message", target: "_top" do %> | |
<%= form_with(model: [@message.room, @message], data: { controller: "reset-form", action: "turbo:submit-end->reset-form#reset" }) do |form| %> | |
<%= form.text_field :content, autocomplete: 'off', placeholder: 'Write your message...' %> | |
<%= button_tag(type: :submit) do %> | |
<i class="fa fa-paper-plane" aria-hidden="true"></i> | |
<% end %> | |
<%= form.submit "Send", data: {disable_with: false} %> | |
<% end %> | |
<% end %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "stimulus" | |
import { Turbo, cable } from "@hotwired/turbo-rails" | |
export default class extends Controller { | |
connect() { | |
console.log('connected'); | |
this.initChannel(); | |
this.scrollBottom(); | |
} | |
initChannel() { | |
const channelName = document.querySelector("turbo-cable-stream-source").getAttribute('channel'); | |
const signedStreamName = document.querySelector("turbo-cable-stream-source").getAttribute('signed-stream-name'); | |
const scrollBottom = this.scrollBottom.bind(this) | |
this.channel = cable.subscribeTo({ 'channel': channelName, 'signed_stream_name': signedStreamName }, { | |
received(data) { | |
setTimeout(scrollBottom, 100); | |
} | |
}); | |
} | |
reset() { | |
this.element.reset() | |
} | |
scrollBottom() { | |
console.log('scroll bottom'); | |
document.querySelector("div.messages").scrollTop = document.querySelector("div.messages").scrollHeight | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment