Skip to content

Instantly share code, notes, and snippets.

@floodico
Created July 5, 2017 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save floodico/a5544116b7cf5ef30759359762195392 to your computer and use it in GitHub Desktop.
Save floodico/a5544116b7cf5ef30759359762195392 to your computer and use it in GitHub Desktop.
user is typing feature
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
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
@Crashtor
Copy link

Crashtor commented Jul 9, 2017

Really helpful. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment