Rails 5 ActionCable 什么时候开始连接?

Rails 5 ActionCable When is a connection is started?

我今天发现了 ActionCable,并且创建了一个非常简单的聊天工具。现在我想把它添加到我当前的项目中。

什么时候建立与频道的连接?在我的简单聊天中,我有一个名为 Welcome 的控制器和一个名为 Demo 的通道。在索引页上,您可以 write/see 消息。我推断当我们访问应用程序的任何页面时,我们会自动连接到该频道? (如果我不在 connection.rb 中添加任何说明)

简答

加载网页时。

长答案

客户端打开与actioncable 通道的连接。根据客户端部分的文档:

http://edgeguides.rubyonrails.org/action_cable_overview.html#client-side-components

当您加载网页时(在您的例子中,欢迎控制器的索引操作)javascript 这样将执行:

// app/assets/javascripts/cable.js
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();
}).call(this);

后跟订阅功能如:

# app/assets/javascripts/cable/subscriptions/chat.coffee
App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }

这就是打开与您定义的频道的连接(如服务器端频道部分中的示例所示):http://edgeguides.rubyonrails.org/action_cable_overview.html#channels

# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  # Called when the consumer has successfully
  # become a subscriber of this channel.
  def subscribed
  end
end

当客户端javascript订阅时,连接最终会指向你的频道对象的subscribed方法。