David has a great video on how to use Action Cable for Rails 5,对我来说,我在Rails 5上使用的是beta 3版本。
问题是,Action Cable是否只适用于只有一个参数作为data
传递的聊天应用?我可以将多个参数传递给speak
吗?
RoomChannel(咖啡):
App.room = App.cable.subscriptions.create "RoomChannel",
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) ->
alert data['message']
# Called when there's incoming data on the websocket for this channel
speak: (message) -> # Could I pass in more than one params?
@perform 'speak', message: message
room_channel.rb:
# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading.
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(data)
ActionCable.server.broadcast 'room_channel', message: data['message']
end
end
如果我可以传递多个参数,那么它适用于哪里:
App.room.speak("foo bar"); # one param so far here.
编辑:
我现在收到两个对象的警报:[object object]
App.room.speak(
{
data1: "Data 1 mate",
data2: "Data 2 mate"
}
)
room.coffee:
received: (data1, data2) ->
alert data1['message']
room_channel.rb:
def speak(data1, data2)
ActionCable.server.broadcast 'room_channel', message: data1['message'], data2['message']
end
控制台:
RoomChannel#speak({"message"=>{"data1"=>"Data 1 mate", "data2"=>"Data 2 mate"}})
答案 0 :(得分:0)
要将另一个参数传递给actioncable服务器,您可以传递Javascript对象。
然后在服务器端,此Javascript对象表示为哈希。
示例:
客户端
App.room.speak(
{
param1: "Data 1 mate",
param2: "Data 2 mate"
}
)
服务器端
def speak(data)
ActionCable.server.broadcast 'room_channel', param1: data['param1'], param2: data['data2']
end
并返回客户端
received: (data) ->
alert data['param1']
alert data["param2"]
答案 1 :(得分:0)
我想我现在可以回答这个问题了。两个参数都被传递但是作为哈希。在控制台中,您将看到两个参数,因此您需要从message
中提取值。
保持speak
方法正常:
def speak(data)
ActionCable.server.broadcast 'room_channel', message: data['message']
end
您的receive
功能(咖啡)应如下所示:
received: (data) ->
alert(data.message.data1)
alert(data.message.data2)
答案 2 :(得分:0)
您必须在广播呼叫上传递哈希值,例如:
def broadcast_to_room_channel(title, message)
data = { title: title, message: message }
ActionCable.server.broadcast 'room_channel', data
end
答案 3 :(得分:0)
我遇到了类似的情况,我需要传递关联的id
参数。我使用了form_with
辅助函数和数据属性,通过语音传递了参数以创建Post
的实例。我发现类似这样的方法有效:
view.html.erb
<%= form_with(model: Post.new) do |f| %>
<div>
<%= f.text_area :content,
id: 'text',
data: { first_id: @first.id, second_id: @second.id } %>
</div>
<% end %>
chat_room.coffee
speak: (post) ->
firstId = document.getElementById('text').dataset.firstId
secondId = document.getElementById('text').dataset.secondId
@perform 'speak', post: post, first_id: firstId, second_id: secondId
chat_room_channel.rb
def speak(data)
Post.create! content: data['post'], first_id: data['first_id'], second_id: data['second_id']
end
在引用的同一视频上,我将broadcast
逻辑移到了一个工作程序中,在这里您将新创建的Post
实例广播到您可以通过{{1}访问的部分内容中}。