这是room.coffee的代码:
App.room = App.cable.subscriptions.create "RoomChannel",
connected: ->
disconnected: ->
received: (data) ->
$('#messages').append "<p>#{data}</p>"
speak: (message) ->
@perform 'speak' , message: message
cable.coffee:
@App ||= {}
App.cable = ActionCable.createConsumer()
rooms.coffee:
$ ->
$messages = $('messages')
$messages.scrollTop $messages.prop('scrollHieght')
$('#message_input').focus()
$(document).on 'keypress','message_input','e'->
if e.keycode == 13 and e.target.value
App.room.speak(e.target.value)
e.target.value = ''
e.preventDefault()
roomchannel:
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(data)
message.create content: data['message']
end
end
Broadcostmessage:
def perform(message)
Actioncable.server.broadcast 'room_channel',render_message(message)
end
private
def render_message(message)
ApplicationController.renderer.render_message
end
创建新消息时,它不会自动加载浏览器的所有消息,直到页面没有重新加载。
答案 0 :(得分:0)
我有类似的问题。尝试在房间视图中包含cable.coffee/js。
<%= javascript_include_tag 'cable', 'data-turbolinks-track': 'reload' %>
您还希望将cable.js添加到/config/initializers/assets.rb。
Rails.application.config.assets.precompile += %w( cable.js )
答案 1 :(得分:0)
谷歌搜索中出现了这个老问题,但有人提到了这个错字:
$messages.scrollTop $messages.prop('scrollHieght')
应该是:
$messages.scrollTop $messages.prop('scrollHeight')