Page-specific ActionCable

喜你入骨 提交于 2019-12-11 11:13:09

问题


Curious what the best practice is for using ActionCable with Turbolinks, when you want to tie a channel with the page being viewed.

The classic example, of course, if you had an article with comments -- how can you stream only those comments related to the article in view and then subscribe to a different channel when viewing a different article?

I've played around with using turbolinks:loaded event on JQuery, but cant figure out what to link that to. Do I want to resubcribe every time? How is that possible without reloading the JS?


回答1:


I managed that by doing something like this:

(Live streaming task output)

$(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



回答2:


Another approach would be to

  1. Move your channel js to a separate directory.
  2. Add your specific channel js to rails asset pipeline.
  3. Edit your application layout and add a content placeholder.
  4. On your specific page, provide content for the aforementioned placeholder and include your specific channel js.

On our blog you will find a more detailed post on how to enable action cable on specific pages.



来源:https://stackoverflow.com/questions/36438323/page-specific-actioncable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!