2016-03-03 75 views
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 

回答

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这是类的名称。

+0

我更新了我的问题,因为我想我可能没有问得很对。我想我也找到了解决方案..正在研究stop_all_streams方法的源代码,并意识到'streams'是ChannelClass中的一个可用变量 – ethayer

1

我认为这是一个可行的解决方案,但它会更好,如果我可以,如果可能的抢确切退订流

发现这个通过查看stop_all_streams方法,因为它提醒我的存在'流'变量。

 
... 
    def unsubscribed 
    streams.each do |stream| 
     ActionCable.server.broadcast stream[0], {id: current_user.id, typing: false} 
    end 
    end 
...