rails 中 actioncable 的默认行为是什么?
What is default behavior for actioncable in rails?
生成新频道时,注释掉stream_from方法调用。我知道,它适合识别流,比如 stream_from "comments_#{message.id}"。
但是如果这个频道没有这样的目标并且应该流式传输所有评论?未指定 stream_from 时此通道的默认行为(可能有价值)是什么?
假设您的频道名为 SomethingChannel
class SomethingChannel < ApplicationCable::Channel
def subscribed
# because you do not need stream_from, then remove the stream_from below
# stream_from "something_channel"
# and just immediately transmit the data. This should be a hash, and thus I use `as_json`; Change this accordingly as you see fit
transmit(Comment.all.as_json)
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
然后在客户端,您只需在需要时调用以下命令即可。
# ...coffee
App.cable.subscriptions.create 'SomethingChannel',
connected: ->
console.log('connected')
# Called when the WebSocket connection is closed.
disconnected: ->
console.log('disconnected')
# `transmit(Comment.all.as_json)` above will invoke this
received: (data) ->
console.log('received')
console.log(data)
您应该会在 Google Chrome / Firefox 控制台中看到如下内容:
connected
received
▼ [{…}]
▶ 0: {id: 1, title: "Hello ", content: "World from Earth! :)", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
▶ 1: {id: 2, title: "Lorem ", content: "Ipsum Dolor", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
length: 2
▶ __proto__: Array(0)
P.S。如果你不打算使用 stream_from
或 stream_for
那么也许你可能根本不需要 ActionCable
,也许你最好从 [=29 检索所有评论=] 而不是(即 GET /comments
)
生成新频道时,注释掉stream_from方法调用。我知道,它适合识别流,比如 stream_from "comments_#{message.id}"。
但是如果这个频道没有这样的目标并且应该流式传输所有评论?未指定 stream_from 时此通道的默认行为(可能有价值)是什么?
假设您的频道名为 SomethingChannel
class SomethingChannel < ApplicationCable::Channel
def subscribed
# because you do not need stream_from, then remove the stream_from below
# stream_from "something_channel"
# and just immediately transmit the data. This should be a hash, and thus I use `as_json`; Change this accordingly as you see fit
transmit(Comment.all.as_json)
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
然后在客户端,您只需在需要时调用以下命令即可。
# ...coffee
App.cable.subscriptions.create 'SomethingChannel',
connected: ->
console.log('connected')
# Called when the WebSocket connection is closed.
disconnected: ->
console.log('disconnected')
# `transmit(Comment.all.as_json)` above will invoke this
received: (data) ->
console.log('received')
console.log(data)
您应该会在 Google Chrome / Firefox 控制台中看到如下内容:
connected
received
▼ [{…}]
▶ 0: {id: 1, title: "Hello ", content: "World from Earth! :)", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
▶ 1: {id: 2, title: "Lorem ", content: "Ipsum Dolor", created_at: "2018-02-13T16:15:05.734Z", updated_at: "2018-02-13T16:15:05.734Z"}
length: 2
▶ __proto__: Array(0)
P.S。如果你不打算使用 stream_from
或 stream_for
那么也许你可能根本不需要 ActionCable
,也许你最好从 [=29 检索所有评论=] 而不是(即 GET /comments
)