我正在使用ActionCable和websocket制作聊天应用程序。
但我无法在room_id
asset/javascripts/channels/rooms.coffee
我希望得到messages.data('room-id')
资产/ Javascript角/信道/ rooms.coffee
jQuery(document).on 'turbolinks:load', ->
messages = $('#messages')
console.log(messages.data('room-id'))
if $('#messages').length > 0
App.room = App.cable.subscriptions.create {
channel: "RoomChannel"
room_id: messages.data('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) ->
$('#messages').append data['message']
speak: (message, room_id) ->
@perform 'speak', message: message, room_id: room_id
$(document).on 'keypress', '[data-behavior~=room_speaker]', (event) ->
if event.keyCode is 13 # return/enter = send
App.room.speak event.target.value
event.target.value = ''
event.preventDefault()
/view/rooms/show.html
<h1><%= @room.title %></h1>
<div id="messages", data-room-id="<%= @room.id %>">
<%= render @room.messages %>
</div>
<form>
<label>Say something:</label><br>
<input type="text" data-behavior="room_speaker">
<hidden> fa</hidden>
</form>
/channels/room_channel.rb
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_#{params[:room_id]}_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(data)
current_user.messages.create!(content: data['message'], room_id: data['room-id'])
end
end
答案 0 :(得分:0)
/view/rooms/show.html
中的空格不对 <div id="messages", data-room-id="<%= @room.id %>">
<div id="messages", data-room-id="<%= @room.id %>">
这是正确的。