ActionCable:如何使用动态频道 [英] ActionCable: How to use dynamic channels
问题描述
我用 Rails 5 和 ActionCable 建立了一个简单的聊天,我有一个简单的聊天"频道.
I have built a simple chat with Rails 5 and ActionCable where i have one simple "chat" channel.
如何使频道订阅和消息广播动态化,以便我可以创建聊天频道并将消息发送到正确的频道?
How can i make the channel subscription and message broadcasting dynamic, so i can create chat channels and have the messages go to the right channels?
不幸的是,我找不到这样的单个代码示例.
I cannot find a single code example of this unfortunately.
更新
下面的答案是正确的.我还发现它现在在 Rails 指南中提到了.不要认为它在 http://edgeguides.rubyonrails.org 之前就在那里/action_cable_overview.html#client-server-interactions-subscriptions
The answer below is correct. I also found it now mentioned in the rails guide. Don't think it was there before http://edgeguides.rubyonrails.org/action_cable_overview.html#client-server-interactions-subscriptions
推荐答案
在 javascripts/channels/room.js
中为您的订阅创建传递一个 roomId:
Pass a roomId on your subscription creation in javascripts/channels/room.js
:
MakeMessageChannel = function(roomId) {
// Create the new room channel subscription
App.room = App.cable.subscriptions.create({
channel: "RoomChannel",
roomId: roomId
}, {
connected: function() {},
disconnected: function() {},
received: function(data) {
return $('#messages').append(data['message']);
},
speak: function(message, roomId) {
return this.perform('speak', {
message: message,
roomId: roomId
});
}
});
$(document).on('keypress', '[data-behavior~=room_speaker]', function(event) {
if (event.keyCode === 13) {
App.room.speak(event.target.value, roomId);
event.target.value = "";
event.preventDefault();
}
return $('#messages').animate({
scrollTop: $('#messages')[0].scrollHeight
}, 100);
});
};
在 channels/room_channel.rb
中,它可以作为订阅创建的参数使用,并且也刚刚使用正确的数据调用了说话动作:
In channels/room_channel.rb
it becomes available as a parameter for the subscription creation, and the speak action was also just called with the correct data:
def subscribed
stream_from "room_channel_#{params[:roomId]}"
end
def speak(data)
Message.create! text: data['message'], room_id: data['roomId']
end
然后,如果您从工作中广播:
And then if you're broadcasting from a job:
def perform(message)
ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message)
end
这篇关于ActionCable:如何使用动态频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!