Created
July 5, 2017 23:11
-
-
Save floodico/a5544116b7cf5ef30759359762195392 to your computer and use it in GitHub Desktop.
user is typing feature
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
jQuery(document).on 'turbolinks:load', -> | |
u = $("#current_user").val() | |
window.current_user = JSON.parse(u) | |
messages = $('#messages') | |
user_is_typing = $('#user_is_typing') | |
App.global_chat = App.cable.subscriptions.create { | |
channel: "ChatRoomsChannel" | |
chat_room_id: messages.data('chat-room-id') | |
}, | |
connected: -> | |
# Called when the subscription is ready for use on the server | |
disconnected: -> | |
# Called when the subscription has been terminated by the server | |
received: (data) -> | |
if data.typing && current_user.id != data.user.id | |
user_is_typing.html "#{data.user.email} is typing" | |
else | |
user_is_typing.html "" | |
is_typing: (typing, chat_room_id) -> | |
@perform 'is_typing', message: {typing: typing}, chat_room_id: chat_room_id | |
$('textarea').on 'focus', (event) -> | |
App.global_chat.is_typing true, messages.data('chat-room-id') | |
return | |
$('textarea').on 'blur', (event) -> | |
App.global_chat.is_typing false, messages.data('chat-room-id') | |
return | |
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
class ChatRoomsChannel < ApplicationCable::Channel | |
def subscribed | |
stream_from "chat_rooms_#{params['chat_room_id']}_channel" | |
end | |
def unsubscribed | |
# Any cleanup needed when channel is unsubscribed | |
end | |
def is_typing(data) | |
ActionCable.server.broadcast "chat_rooms_#{params['chat_room_id']}_channel", typing: data['typing'], user: current_user | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Really helpful. Thanks!