将用户添加到actioncable频道而不刷新页面。

时间:2018-06-10 16:56:25

标签: ruby-on-rails actioncable

当我提到actioncable频道时,我指的是:actioncable_channel

创建聊天室+ chatroom_users后,用户必须刷新页面才能连接到特定的chatroom_id频道。是否可以在不重新加载页面的情况下连接到该频道?

1 个答案:

答案 0 :(得分:1)

可以在视图中的自定义操作(而不是页面刷新)上创建连接。请看下面的代码,

createconusmer = (send_params) ->
  App.chatbot = App.cable.subscriptions.create { channel: "ChatbotChannel" , auth_token: send_params , url: string },
      connected:  ->
        # Called when the subscription is ready for use on the server

      disconnected: ->
        # Called when the subscription has been terminated by the server

      received: (data) ->
        console.log(data)

      speak: (data, responder, payload) ->
          @perform 'speak' , message: data , responder: responder , payload: payload 

现在您可以在咖啡文件中定义自定义功能,

nameclick = (value) ->
    createconusmer value

window["nameclick"] = nameclick

现在在您的视图中,您可以使用功能名称单击来创建新的流媒体。另外,我添加了一些代码以确保它们是唯一的,以避免添加重复连接。

connections = []

addConnection = (id) ->
  connections.push(id)

removeConnection = (id) ->
  index = connections.indexOf(id)
  connections.splice(index, 1) if index > -1

connectedTo = (id) ->
  connections.indexOf(id) > -1

nameclick = (value) ->
  if connectedTo(value) == false
    addConnection(value)
    createconusmer value