行动有线频道订阅不起作用,因为频道方法未执行



我在Rails的一家小书店工作。用户可以为添加到产品页面的单个书籍撰写评论。我想使用 ActionCable 向页面添加新评论,以便它始终保持最新状态,并在为当前位于同一页面上的其他用户添加评论时显示一个小的警报通知。

因此,我想根据产品的 ID 为每个产品设置单独的渠道。当用户打开产品页面时,她应该订阅相应的频道。

为了实现这一点,我正在尝试调用一个名为listen的方法,每当通过调用 JS 中的App.product.perform('listen', {product_id: 1})新站点加载新站点时,我都会将其添加到 ProductChannel 类中。但问题是,尽管调用了perform,但从未执行listen。我做错了什么或误解了什么?提前感谢!

javascript/channels/prouduct.coffee内容 :

App.product = App.cable.subscriptions.create "ProductChannel",
connected: () ->
return
disconnected: ->
# Called when the subscription has been terminated by the server
return
received: (data) ->
# Called when there's incoming data on the websocket for this channel
console.log("there is data incoming so lets show the alert")
$(".alert.alert-info").show()
return
listen_to_comments: ->
@perform "listen", product_id: $("[data-product-id]").data("product-id")
$(document).on 'turbolinks:load', ->
App.product.listen_to_comments()
return

channels/product_channel.rb内容 :

class ProductChannel < ApplicationCable::Channel
def subscribed
end
def unsubscribed
end
def listen(data)
stop_all_streams
stream_for data["product_id"]
end
end

必须实例化连接对象:

module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags current_user.name
end
def disconnect
# Any cleanup work needed when the cable connection is cut.
end
protected
def find_verified_user
if current_user = User.find_by_identity cookies.signed[:identity_id]
current_user
else
reject_unauthorized_connection
end
end
end
end

然后你需要broadcast_to@product

class ProductChannel < ApplicationCable::Channel
def subscribed
@product = Product.find(params[:product_id])
end
def unsubscribed
stop_all_streams
end
def listen(data)
stream_for @product
ProductsChannel.broadcast_to(@product)
end
end

相关内容

最新更新