Dra*_*kic 3 ruby-on-rails-5 actioncable
我与Rails 5和ActionCable建立了一个简单的聊天,我有一个简单的"聊天"频道.
如何使频道订阅和消息广播动态化,以便创建聊天频道并将消息发送到正确的频道?
遗憾的是,我找不到一个代码示例.
更新
以下答案是正确的.我也发现它现在在导轨指南中提到过.在http://edgeguides.rubyonrails.org/action_cable_overview.html#client-server-interactions-subscriptions之前不要认为它在那里
Las*_*ser 11
在您的订阅创建中传递roomId 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);
});
};
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
然后,如果你从一份工作广播:
def perform(message)
ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message)
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3053 次 |
| 最近记录: |