0
私はActionCableでゲームルーム(ゲーム)内でチャットを実装しています。ここ は、これまでの私のコードです:ActionCable複数のチャンネルにメッセージを表示
アプリ/チャンネル/ game_channel.rb:
class GameChannel < ApplicationCable::Channel
def subscribed
stream_from "game_channel_#{params[:game]}"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak (data)
ActionCable.server.broadcast("game_channel_#{params[:game]}", data)
end
end
アプリ/資産/ JavaScriptの/チャンネル/ game.js.erb:
<% Game.all.each do |game| %>
App['game' + <%=game.id%>] = App.cable.subscriptions.create({channel: 'GameChannel', game: <%= game.id %>}, {
received: function(data) {
alert(message)
},
setGameId: function(gameId) {
this.gameId = gameId
},
speak: function(data) {
this.perform('speak'), message => data['message']
}
});
<% end %>
Iコマンドを送信:
App.game1.speak (message: "Test1", player: 1, game:1)
- >は、メッセージのアラート: "Test1を" @ゲーム1.
App.game2.speak (message: "Hello", player: 2, game:2)
- >それはMSGに警告メッセージ "こんにちは" @ゲーム2、と@ゲーム1をアラート:再び "Test1を"。
どのようにこれを修正するには、更新されたゲーム@だけメッセージを表示し、他のゲームの部屋で更新することはありませんか?
Serverが表示されます。ここでは
17:03:01 web.1 | GameChannel is transmitting the subscription confirmation
17:03:01 web.1 | GameChannel is streaming from game_channel_2
17:03:01 web.1 | GameChannel is transmitting the subscription confirmation
17:03:01 web.1 | GameChannel is streaming from game_channel_1
17:03:06 web.1 | GameChannel#speak
17:03:06 web.1 | [ActionCable] Broadcasting to game_channel_1: {"action"=>"speak"}
17:03:06 web.1 | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_1)
17:03:06 web.1 | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_1)
17:03:11 web.1 | GameChannel#speak
17:03:11 web.1 | [ActionCable] Broadcasting to game_channel_2: {"action"=>"speak"}
17:03:11 web.1 | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_2)
17:03:11 web.1 | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_2)