您的订阅创建传递一个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);
});
};
在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
真棒谢谢你今晚试试吧 –
当你有多个聊天室时,这是如何工作的?如何使用您的示例订阅roomA和roomB并根据用户是否拥有访问权限在服务器上对其进行授权? –
然后如何将@ room.id从控制器传递到room.js? – icemelt