我与Rails 5和ActionCable建立了一个简单的聊天,我有一个简单的聊天"信道。
如何使频道订阅和消息广播动态化,以便创建聊天频道并将消息发送到正确的频道?
遗憾的是,我找不到一个代码示例。
更新
以下答案是正确的。我也发现它现在在导轨指南中提到过。在http://edgeguides.rubyonrails.org/action_cable_overview.html#client-server-interactions-subscriptions
之前不要认为它存在答案 0 :(得分:11)
在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
中,它可用作订阅创建的参数,而且只是使用正确的数据调用了发言操作:
def subscribed
stream_from "room_channel_#{params[:roomId]}"
end
def speak(data)
Message.create! text: data['message'], room_id: data['roomId']
end
然后,如果你正在从一份工作中广播:
def perform(message)
ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message)
end