如何使用App.cable.subscriptions.remove删除Rails 5中的actioncable频道订阅?

Las*_*ser 7 javascript ruby-on-rails websocket ruby-on-rails-5 actioncable

要创建订阅,我运行:

  App.room = App.cable.subscriptions.create({
    channel: "RoomChannel",
    roomId: roomId
  }, {
    connected: function() {},
    disconnected: function() {},
    received: function(data) {
      return $('#messages').append(data['message']);
    },
    speak: function(message, roomId) {
      return this.perform('speak', {
        message: message,
        roomId: roomId
      });
    }
  });
Run Code Online (Sandbox Code Playgroud)

但是因为我希望客户端永远不会订阅多个频道,所以我每次都可以在此之前运行什么来删除客户端的所有订阅?

我试着做一些超级hacky的事情:

App.cable.subscriptions['subscriptions'] = [App.cable.subscriptions['subscriptions'][1, 0]]
Run Code Online (Sandbox Code Playgroud)

但我确信它不起作用,因为有许多其他组件进入订阅/取消订阅.

App.cable.subscriptions.remove需要一个订阅参数,但我传递了什么?

谢谢!

小智 6

有点迟到的答案,但考虑到你已经宣布了

App.room = App.cable.subscriptions.create(...)

删除,像

if (App.room) App.cable.subscriptions.remove(App.room);

应该足够了.


Las*_*ser 3

在每次创建订阅之前运行此命令将确保每个客户端最多只有一个订阅。

if (App.cable.subscriptions['subscriptions'].length > 1) {
    App.cable.subscriptions.remove(App.cable.subscriptions['subscriptions'][1])
};
Run Code Online (Sandbox Code Playgroud)