在您的订阅创建中传递一个 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