问题描述
我正在尝试使用 Action Cable 创建一个简单的类似聊天的应用程序(规划扑克应用程序).我对术语、文件层次结构以及回调的工作方式有点困惑.
I'm trying to create a simple chat-like application (planning poker app) with Action Cable. I'm a little bit confused by the terminology, files hierarchy and how the callbacks work.
这是创建用户会话的操作:
This is the action that creates user session:
class SessionsController < ApplicationController
def create
cookies.signed[:username] = params[:session][:username]
redirect_to votes_path
end
end
然后用户可以发布应该向所有人广播的投票:
A user can then post a vote that should be broadcasted to everyone:
class VotesController < ApplicationController
def create
ActionCable.server.broadcast 'poker',
vote: params[:vote][:body],
username: cookies.signed[:username]
head :ok
end
end
到目前为止,一切对我来说都很清楚并且工作正常.问题是 - 如何显示已连接用户的数量?当用户(消费者?)连接时,JS 中是否会触发回调?我想要的是当我以隐身模式在 3 个不同的浏览器中打开 3 个标签时,我想显示3".当新用户连接时,我希望数字递增.如果任何用户断开连接,则该数字应递减.
Up to this point everything is clear for me and works fine. The problem is - how do I display the number of connected users? Is there a callback that fires in JS when a user (consumer?) connects? What I want is when I open 3 tabs in 3 different browsers in incognito mode I would like to display "3". When a new user connects, I would like the number to increment. If any user disconnects, the number should decrement.
我的PokerChannel
:
class PokerChannel < ApplicationCable::Channel
def subscribed
stream_from 'poker'
end
end
app/assets/javascripts/poker.coffee
:
App.poker = App.cable.subscriptions.create 'PokerChannel',
received: (data) ->
$('#votes').append @renderMessage(data)
renderMessage: (data) ->
"<p><b>[#{data.username}]:</b> #{data.vote}</p>"
推荐答案
好像是一种方式使用
ActionCable.server.connections.length
(见评论中的注意事项)
(See caveats in the comments)
这篇关于ActionCable - 如何显示已连接用户的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!