2

是否可以将未订阅的频道“名称”返回给未订阅的方法?

当用户取消订阅频道时(由于断开连接或导航离开),我需要确保客户端标志设置为空状态。我已经创建了一个清理方法,但是我无法找出清理消息应该发送到哪个频道。因为我无法获取取消订阅的方法是从哪个频道调用的。

class ConversationChannel < ApplicationCable::Channel
  def follow(data)
    stop_all_streams
    conversation = Conversation.find(data['conversation_id'])
    if conversation.is_participant?(current_user)
      stream_from "conversation:#{data['conversation_id']}"
    end
  end

  def unsubscribed
    clear_typing
  end

  ...

  def clear_typing
    # need way to find out conversation_id of the unsubscribed stream
    ActionCable.server.broadcast "conversation:#{data['conversation_id']}", {id: current_user.id, typing: false}
  end
end
4

2 回答 2

1

我相信类名是频道名。

来自ActionCable文档:

# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
  def subscribed
    current_user.appear
  end

  def unsubscribed
    current_user.disappear
  end

  def appear(data)
    current_user.appear on: data['appearing_on']
  end

  def away
    current_user.away
  end
end

客户端订阅如下:

# app/assets/javascripts/cable/subscriptions/appearance.coffee
App.cable.subscriptions.create "AppearanceChannel",
  # Called when the subscription is ready for use on the server
  connected: ->
    @install()
    @appear()

  # Called when the WebSocket connection is closed
  disconnected: ->
    @uninstall()

  # Called when the subscription is rejected by the server
  rejected: ->
    @uninstall()

  appear: ->
    # Calls `AppearanceChannel#appear(data)` on the server
    @perform("appear", appearing_on: $("main").data("appearing-on"))

  away: ->
    # Calls `AppearanceChannel#away` on the server
    @perform("away")


  buttonSelector = "[data-behavior~=appear_away]"

  install: ->
    $(document).on "page:change.appearance", =>
      @appear()

    $(document).on "click.appearance", buttonSelector, =>
      @away()
      false

    $(buttonSelector).show()

  uninstall: ->
    $(document).off(".appearance")
    $(buttonSelector).hide()

如果您仔细观察,客户端正在订阅AppearanceChannel该类名称的频道。

于 2016-03-03T18:20:08.907 回答
1

我认为这是一个可能的解决方案,但如果可能的话,如果我能抓住确切的未订阅流会更好:

通过查看 stop_all_streams 方法发现了这一点,因为它提醒我存在“流”变量。

...
  默认取消订阅
    stream.each 做 |stream|
      ActionCable.server.broadcast stream[0], {id: current_user.id, typing: false}
    结尾
  结尾
...
于 2016-03-03T18:57:20.100 回答