特定页面的 ActionCable

Jar*_*red 1 ruby-on-rails turbolinks actioncable

想知道当您想将频道与正在查看的页面联系起来时,将 ActionCable 与 Turbolinks 结合使用的最佳实践是什么。

一个经典的例子,当然,如果你有一篇带有评论的文章——你怎么能只流式传输与查看的文章相关的那些评论,然后在查看不同的文章时订阅不同的频道?

turbolinks:loaded在 JQuery上使用过事件,但不知道将它链接到什么。我想每次都重新订阅吗?不重新加载JS怎么可能?

sie*_*y22 5

我通过做这样的事情来做到这一点:

(直播任务输出)

$(document).on 'turbolinks:load', -> # use page:change if your on turbolinks < 5
  if document.getElementById("task-output") # if a specific field is found 
    App.task = App.cable.subscriptions.create { channel: "TaskChannel", task_id: task_id },
      received: (data) ->
        # do something with your data
  else if App.task # if I'm not on the page where I want to be connected, unsubscribe and set it to null
    App.task.unsubscribe()
    App.task = null
Run Code Online (Sandbox Code Playgroud)